user3354212 user3354212 - 1 month ago 5
R Question

how to switch characters in a data frame in r

I have a data frame:

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


I would like to switch "0" and "1" each other. The result is expected:

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


It can be done by replace "0" to an intermediate value such as "2" or whatever, then replace "1" to "0", and replace the intermediate value back to "1". is there any efficient way to do this? Thanks.

Answer

We can use chartr to replace 1 with 0 and viceversa. Loop through the columns (lapply(df1[-1], ) and change the characters with 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

data

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