简体   繁体   English

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

[英]How to apply a function to several variables in R?

I have a simple/confusing question in R. 我在R中有一个简单/令人困惑的问题。

Here is an example of my problem. 这是我的问题的一个例子。

I have a string of numbers or characters: 我有一串数字或字符:

data <- c(1,2,3,4,5)

and I have a function which I want to apply to several variables in the string. 并且我有一个函数想要应用于字符串中的多个变量。

dd <- function(d){if(d==data[1:3]) 'yes'
else 'no'}

but when I apply the function to the string I got this error 但是当我将函数应用于字符串时出现此错误

unlist(lapply(data,dd))

Warning message: 警告信息:

   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

So, My question is how can I apply the function to several variables in the string not just for the first element? 因此,我的问题是如何将函数应用于字符串中的多个变量,而不仅仅是第一个元素? to get an output like 得到像这样的输出

"yes" "yes" "yes" "no" "no"

Thanks in Advance, 提前致谢,

There is no need for a lapply loop. 不需要lapply循环。 You can use the vectorized ifelse and need to use %in% : ifelse(d %in% data[1:3], "yes", "no") 您可以使用向量化ifelse并需要使用%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)? 它可以工作,但是我如何将其应用于例如:如果我想对c(1,2)使用'yes',对其余部分(4,5)使用'no'表示'3'和'None'?

There are several ways to achieve that. 有几种方法可以实现这一目标。 You could use a nested ifelse . 您可以使用嵌套的ifelse However, in the specific example I would use cut : 但是,在特定示例中,我将使用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