简体   繁体   中英

How to apply a function to several variables in R?

I have a simple/confusing question in 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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