Reputation: 961
Following an example given in the dplyr::case_when()
documentation:
x <- 1:50
case_when(x %% 35 == 0 ~ "fizz buzz",
x %% 5 == 0 ~ "fizz",
x %% 7 == 0 ~ "buzz",
TRUE ~ as.character(x))
I expect that the number 35
will produce "buzz"
but it produces "fizz buzz"
My reasoning is that case_when()
evaluates all statements one by one regardless if a previous one is true or not (since it does evaluate TRUE ~ as.character(x)
which is the last one) and that 35 %% 7
is obviously 0.
What am I missing?
Upvotes: 2
Views: 3645
Reputation: 500
case_when() evaluates all statements one by one regardless if a previous one is true or not (since it does evaluate TRUE ~ as.character(x) which is the last one)
This is misleading, the output of case_when()
is based on the first statement that is true.
TRUE ~ as.character(x)
means that if x is not divisible by 5 or 7 then then x will be returned as a string ie for x = 5, "5" will be returned.
If x is divisible by 5 or 7, casewhen()
does not evaluate subsequent cases. "fizz" and "buzz" are not passed to as.character(x)
and they do not have to be because they are already character strings.
Upvotes: 3