2

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!

shbrainard
  • 377
  • 2
  • 9
  • @GruelingPine185 I think you just fell into the hole ScottB is afraid of: after your second call everything is zero: the the original zeros became ones, and then all ones (which will be everything) become zero. – Dirk Eddelbuettel Mar 11 '21 at 01:46
  • Omg. In my head everything works out, but gosh I didn't catch that. Thx for bringing it to my attention :) –  Mar 11 '21 at 01:51

1 Answers1

5

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"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213