简体   繁体   中英

dplyr mutate_at: create new variables with recode

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

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 (eg if.else or if_else ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM