If statement true then modify several columns

Viewed 45

I would like to do several actions in dplyr pipe when some statement is true.

For such data:

t = tibble(a = 1:3, b = 1:3, c = 1:3, d = 1:3, e = 1:3)

I would like to write somehow that if

a == 2

then

b = b + 2
c = c + 3
d = d + 4
e = e + 5

Basically, I do not want to repeat the if condition several times because if it changed I would need to update it in several places which is error-prone.

1 Answers

We can use

library(dplyr)
library(purrr)
map_dfc(2:5, ~ {n <- .x ;
               t %>%
                  transmute_at(vars(.x), ~  case_when(a == 2 ~  . + n, TRUE ~ .))}) %>%
   bind_cols(select(t, a), .)

If we need different values, then use map2

map2_dfc(2:5, c(2L, 1000L, 1500L, 2000L), ~ {n <- .x
               val <- .y;
              t %>%
                  transmute_at(vars(.x), ~  case_when(a == 2 ~  . + val, TRUE ~ .))}) %>%
   bind_cols(select(t, a), .)
Related