Replace "1" with "0" and "0" with "1" simultaneously in R

Viewed 83

I have a character vector in R such as:

> row
"1/1" "0/0" "0/0" "1/1" "0/1" "0/0" "1/0" 

I would like to swap the "1" and "0" characters in order to return a vector:

> row2
"0/0" "1/1" "1/1" "0/0" "1/0" "1/1" "0/1"

I feel like this is a simple task, but I am getting confused since I assume multiple calls to gsub for instance will reverse the conversion process on the second call.

Any ideas for an R-based solution to this? Thanks!

1 Answers

You can use chartr :

row <- c("1/1", "0/0", "0/0", "1/1", "0/1", "0/0", "1/0" )
chartr('01', '10', row)
#[1] "0/0" "1/1" "1/1" "0/0" "1/0" "1/1" "0/1"
Related