Search code examples
rreplaceswap

Replacing and swapping one value by another in R for specific rows


In the following data frame, how can I replace all 1 by 2 and all 2 by 1, and keep 3 as it is

mydf=structure(list(x1 = c(1L, 2L, 3L, 1L), x2 = c(2L, 1L, 2L, 3L), 
               x3 = c(1L, 2L, 2L, 1L), x4 = c(1L, 2L, 1L, 1L)), row.names = 5:8, class = "data.frame")
mydf

  x1 x2 x3 x4
5  1  2  1  1
6  2  1  2  2
7  3  2  2  1
8  1  3  1  1

Any kind of help is appreciated.


Solution

  • Base R :

    mydf[] <- lapply(mydf, function(x) ifelse(x == 1, 2, ifelse(x == 2, 1, x)))
    

    dplyr :

    library(dplyr)
    mydf %>%
      mutate(across(.fns = ~case_when(. == 2 ~ 1L,. == 1 ~ 2L, TRUE ~ .)))
    
    #  x1 x2 x3 x4
    #5  2  1  2  2
    #6  1  2  1  1
    #7  3  1  1  2
    #8  2  3  2  2