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

时间:2015-10-06 08:04:40

标签: r string function lapply

我在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 个答案:

答案 0 :(得分:1)

There is no need for a lapply loop. You can use the vectorized ifelse and need to use %in%: ifelse(d %in% data[1:3], "yes", "no")

Answering the follow-up question in your comment:

It works but how can I apply this to for example: if I want to have 'yes' for c(1,2) and 'no' for '3' and 'None' to the rest (4,5)?

There are several ways to achieve that. You could use a nested ifelse. However, in the specific example I would use cut:

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