2015-10-06 35 views
0

我有一个简单/令人困惑的问题R.如何将函数应用于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" 

由于事先

+1

无需一个'lapply'循环:'ifelse(d%以%数据[1:3], “是”, “否”)' – Roland

+0

它的工作原理,但我怎么能适用于这个例如: 如果我想'是'为c(1,2)和'不'为'3'和'无'其余(4,5)? 有没有其他方法可以将这三个条件结合在一起? 据我所知只能定义2条件ifelse(如是/否) – user3576287

回答

1

没有必要为lapply循环。您可以使用矢量ifelse,并需要使用%in%ifelse(d %in% data[1:3], "yes", "no")

回答您的评论的后续问题:

它的工作原理,但我怎么能应用此例如:如果我想有对于c(1,2)是'是',对'3'是'不',对其余(4,5)是'不'。

有几种方法可以实现这一点。你可以使用嵌套的ifelse。然而,在特定示例中,我会用cut

cut(data, breaks = c(-Inf, 2, 3, Inf), labels = c("yes", "no", "None")) 
#[1] yes yes no None None 
#Levels: yes no None 
+0

我发现了另一种方式使用嵌套ifelse! 感谢您的帮助罗兰! :) – user3576287

相关问题