1
votes

I can't create multiple reversed variables with dplyr.

Definition of the problem:

df <- data.frame (V1 =c (1,2,2,1,2), V2 = c(2,2,1,2,2), V3 = c(3,5,2,1,4))

I want to invert values 1 and 2 in the first 2 variables.
I've tried many things, but nothing works.

I want to obtain

V1  V2  V3
2   1   3
1   1   5
1   2   2
2   1   1
1   1   4
1
thanks. I'm looking to use mutate_at. Any solution?R. Ladwein
df %>% mutate_at(vars(V1:V2), ~if_else(. == 1, 2, 1))Ronak Shah
Is this just new <- 3 - old?Rui Barradas

1 Answers

1
votes

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).