【发布时间】:2015-10-06 08:04:40
【问题描述】:
我在 R 中有一个简单/令人困惑的问题。
这是我的问题的一个例子。
我有一串数字或字符:
data <- c(1,2,3,4,5)
我有一个函数,我想将它应用于字符串中的几个变量。
dd <- function(d){if(d==data[1:3]) 'yes'
else 'no'}
但是当我将函数应用于字符串时,我得到了这个错误
unlist(lapply(data,dd))
警告信息:
1: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
2: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
3: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
4: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
5: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
所以,我的问题是如何将函数应用于字符串中的多个变量,而不仅仅是第一个元素? 得到类似的输出
"yes" "yes" "yes" "no" "no"
提前致谢,
【问题讨论】:
-
不需要
lapply循环:ifelse(d %in% data[1:3], "yes", "no") -
它有效,但我如何将其应用于例如:如果我想对 c(1,2) 使用“是”,对“3”使用“否”,对其余使用“无” (4,5)?有没有其他方法可以在 ifelse 中结合这三个条件?据我所知,只能为 ifelse 定义 2个条件(如是/否)