3
I created a function to automatically check if the value of a column is contained in a list. I could do dplyr::mutate + dplyr::ifelse, but as they are for many columns, it would be a very long code. Function works out of mutate, but not in it.
What I did:
see_if_succed <- function(x,y){
if (x %in% y) {
1
} else {
0
}
}
Outside the pipe the function works:
succeed <- c(1,5,8,9)
see_if_succed(100,succeed)
#0
But not inside the pipe:
succeed <- c(1,5,8,9)
a <- c("A","B", "C")
b <- c(1,2,1)
y <- data.frame(a,b)
library(dplyr)
y %>%
mutate(z = see_if_succed(b, succeed))
# a b z
# 1 A 1 1
# 2 B 2 1
# 3 C 1 1
# Warning message:
# Problem with `mutate()` input `z`.
# i the condition has length > 1 and only the first element will be used
# i Input `z` is `see_if_succed(b, succeed)`.
Could someone tell me how I make this function work on a dataframe?