I am trying to mutate a new column in an R tibble which is a logical equation of existing factor columns. I keep encountering the error the condition has length > 1
despite the simple control flow of my problem. My actual code has a more complex logical flow and works fine on some factor columns but not others.
Here is an MRE:
my_tibble <- tibble::tibble(a = as.factor(c("dog","cat","dog")), b = as.factor(c(1,5,6)))
my_fn <- function(a, b){
if (a == "dog"){
if (b == 1){
return(12)
}
else{
return(3)
}
} else{
return(5)
}
}
dplyr::mutate(my_tibble, c = my_fn(a,b)) # Error here!
However, my_tibble[1,1] == "dog"
evaluates to TRUE
.
The error itself is:
Error in `mutate()`:
ℹ In argument: `c = my_fn(a, b)`.
Caused by error in `if (a == "dog") ...`:
! the condition has length > 1
I have to imagine there is something about logical expressions involving factors I am missing here. Any guidance is much appreciated.
type here
user974087 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.