如何在r中的数据帧中切换字符

use*_*212 1 r

我有一个数据框:

ID        S01       S02       S03       S04       S05
M01       0|1       0|0       1|1       1|1       1|1
M02       0|0       0|0       0|0       1|1       1|0
M03       0|0       0|0       0|0       1|1       0|0
M04       0|1       0|1       0|1       0|0       0|1
M05       0|0       0|0       0|0       1|1       0|0
Run Code Online (Sandbox Code Playgroud)

我想互相切换"0"和"1".结果是预期的:

ID        S01       S02       S03       S04       S05
M01       1|0       1|1       0|0       0|0       0|0
M02       1|1       1|1       1|1       0|0       0|1
M03       1|1       1|1       1|1       0|0       1|1
M04       1|0       1|0       1|0       1|1       1|0
M05       1|1       1|1       1|1       0|0       1|1
Run Code Online (Sandbox Code Playgroud)

可以通过将"0"替换为中间值(例如"2"或其他)来完成,然后将"1"替换为"0",并将中间值替换回"1".有没有有效的方法来做到这一点?谢谢.

akr*_*run 7

我们可以用chartr0代替1,反之亦然.循环遍历列(lapply(df1[-1],)并使用更改字符chartr

df1[-1] <- lapply(df1[-1], chartr, old = '01', new = '10')
df1
#   ID S01 S02 S03 S04 S05
#1 M01 1|0 1|1 0|0 0|0 0|0
#2 M02 1|1 1|1 1|1 0|0 0|1
#3 M03 1|1 1|1 1|1 0|0 1|1
#4 M04 1|0 1|0 1|0 1|1 1|0
#5 M05 1|1 1|1 1|1 0|0 1|1
Run Code Online (Sandbox Code Playgroud)

数据

df1 <- structure(list(ID = c("M01", "M02", "M03", "M04", "M05"),
S01 = c("0|1", 
"0|0", "0|0", "0|1", "0|0"), S02 = c("0|0", "0|0", "0|0", "0|1", 
"0|0"), S03 = c("1|1", "0|0", "0|0", "0|1", "0|0"), S04 = c("1|1", 
"1|1", "1|1", "0|0", "1|1"), S05 = c("1|1", "1|0", "0|0", "0|1", 
"0|0")), .Names = c("ID", "S01", "S02", "S03", "S04", "S05"),
class = "data.frame", row.names = c(NA, -5L))
Run Code Online (Sandbox Code Playgroud)