neves
neves

Reputation: 846

Why can't use ifelse directly on lapply?

I have a data:

df_1 <- data.frame(
  x = c(0, 1, 0, 2, 0), 
  y = c(0, 2, 1, 2, 1), 
  z = c(0, 2, 1, 2, 1)
)

And this function:

lapply(X = df_1, FUN = function(x) {
  ifelse(test = x >= 1, yes = 'OK', 'NO_OK')
})

It's ok. But, when use ifelse "directly":

lapply(X = df_1, FUN = ifelse, df_1 >= 1, yes = 'OK', no = 'NO_OK')

But, this works:

lapply(X = df_1, FUN = sum, na.rm = TRUE)

Why does the first function work and the second does not? What is the theoretical explanation for this?

Upvotes: 0

Views: 44

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

From ?lapply

... optional arguments to FUN.

So ... are the additional arguments to function. Here what you are trying to do add an additional condition on input that does not work "directly". For example, if your data was :

df_1 <- data.frame(
   x = c(TRUE, FALSE, TRUE, FALSE, TRUE), 
   y = c(TRUE, FALSE, FALSE, FALSE, TRUE)
)

Using anonymous function you could have done :

lapply(X = df_1, FUN = function(x) {
   ifelse(test = x, yes = 'OK', 'NO_OK')
})

and this would have worked without anonymous function as well.

lapply(X = df_1, FUN = ifelse, yes = 'OK', no = 'NO_OK')

Since we are not changing the input here and we are using it as it is hence, it works.

In your original data, we are not using the input as it is, we have an additional condition to check i.e (x >= 1) hence anonymous function is needed.

Upvotes: 2

Related Questions