在 R 中为特定行替换和交换一个值

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

在下面的数据框中,如何将所有 1 替换为 2 并将所有 2 替换为 1,并保持 3 不变是

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

感谢任何形式的帮助。

基础 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