Piotr K
Piotr K

Reputation: 1025

Difference in behavior between if_else and case_when with group_by

I can't figure out why these two are not behaving in the same way. The case_when one works as I expect it to, while if_else one gives the error:

Error: `true` must be length 1 (length of `condition`), not 2 
Run `rlang::last_error()` to see where the error occurred.

The example code:

tb <-
  tibble(DC = c(1, 1, 2), ID = c(1, 1, 2), V = c(100, 200, 400)) %>% 
  group_by(DC, ID)

tb %>%
  mutate(V = if_else(sum(V) == 300, V / n(), 1))

tb %>% 
  mutate(V = case_when(sum(V) == 300 ~ V / n(), TRUE ~ 1))

Thanks in advance.

Upvotes: 2

Views: 411

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388972

That is because true and false values in if_else should be of same length as condition. Here, condition is of length 1 (sum(V) == 300) whereas true value for 1st group is of length 2 (V / n()) hence, the error.

Since this is a scalar comparison you can use if/else instead.

library(dplyr)

tb %>% mutate(V = if(sum(V) == 300) V / n() else 1)

#    DC    ID     V
#  <dbl> <dbl> <dbl>
#1     1     1    50
#2     1     1   100
#3     2     2     1

Upvotes: 1

Related Questions