繁体   English   中英

如何将函数应用于R中的几个变量?

[英]How to apply a function to several variables in 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"

提前致谢,

不需要lapply循环。 您可以使用向量化ifelse并需要使用%in%ifelse(d %in% data[1:3], "yes", "no")

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

它可以工作,但是我如何将其应用于例如:如果我想对c(1,2)使用'yes',对其余部分(4,5)使用'no'表示'3'和'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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM