我在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
循环。您可以使用vectorizedifelse
并需要使用%in%
:ifelse(d %in% data[1:3], "yes", "no")
在您的评论中回答后续问题:
它可以工作,但是我如何将其应用于例如:如果我想对c(1,2)使用'yes',对其他3(4,5)使用'no',对于'3'使用'none',而对其余(4,5)使用'None'?
有几种方法可以实现这一目标。您可以使用嵌套的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句