【问题标题】:How to apply a function to several variables in R?如何将函数应用于R中的多个变量?
【发布时间】: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个条件(如是/否)

标签: r string function lapply


【解决方案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

【讨论】:

  • 我通过使用嵌套 ifelse 找到了另一种方式!感谢您的帮助罗兰! :)
猜你喜欢
  • 2020-02-25
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多