& is the elementwise operation. But && is the bitwise operation. It’s just easier to see the differences through examples.
1 2 3 4 |
library(dplyr) data <- data.frame(gender = c('m', 'm', 'f', 'm', 'm'), grade = c(1,4,4,2,3)) |
1 2 3 4 5 6 7 8 |
> data %>% mutate( + new = ifelse(gender == 'm' & grade > 2, "abc","def")) gender grade new 1 m 1 def 2 m 4 abc 3 f 4 def 4 m 2 def 5 m 3 abc |
But if we use &&,
1 2 |
data %>% mutate( new = ifelse(gender == 'm' && grade > 2, "abc","def")) |
1 2 3 4 5 6 7 8 |
> data %>% mutate( + new = ifelse(gender == 'm' && grade > 2, "abc","def")) gender grade new 1 m 1 def 2 m 4 def 3 f 4 def 4 m 2 def 5 m 3 def |
The result from the first observation will be applied to the subsequent observations.