There are a variety of ways to attack this. A simple case_when
statement would suffice:
library(tidyverse)
df <- data.frame(
V1 =c (1,2,2,1,2),
V2 = c(2,2,1,2,2),
V3 = c(3,5,2,1,4)
)
df
#> V1 V2 V3
#> 1 1 2 3
#> 2 2 2 5
#> 3 2 1 2
#> 4 1 2 1
#> 5 2 2 4
df %>%
mutate(
V1 = case_when(V1 == 1 ~ 2, V1 == 2 ~ 1),
V2 = case_when(V2 == 1 ~ 2, V2 == 2 ~ 1)
)
#> V1 V2 V3
#> 1 2 1 3
#> 2 1 1 5
#> 3 1 2 2
#> 4 2 1 1
#> 5 1 1 4
But since you said mutate_at
, you probably want to use a function:
flip_ones_and_twos <- function(x) {
return(x %% 2 + 1)
}
df %>%
mutate_at(vars(V1, V2), ~ flip_ones_and_twos(.))
#> V1 V2 V3
#> 1 2 1 3
#> 2 1 1 5
#> 3 1 2 2
#> 4 2 1 1
#> 5 1 1 4
I'm certain there are other approaches as well (e.g. if.else
or if_else
).
df %>% mutate_at(vars(V1:V2), ~if_else(. == 1, 2, 1))
– Ronak Shahnew <- 3 - old
? – Rui Barradas