Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap values across multiple columns by a condition

Tags:

r

I have a data frame like this:

df = read.table(text="IDX     D1     D2       D3     D4      D5       D6      D7
 F     0/0     1/1     0/0     0/1     1/1     0/0     0/0
 F     1/1     0/0     0/0     0/0     0/0     1/1     0/0
 T     0/0     0/0     0/0     0/0     0/0     0/0     0/0
 T     0/1     0/1     0/0     1/1     0/1     0/0     0/1
 F     1/1     0/1     1/1     0/0     0/1     0/0     0/0", header=T, stringsAsFactors=F)

I would like to swap the characters between 0 and 1 if df$IDX==F

The expected result:

 IDX     D1     D2       D3     D4      D5       D6      D7
  F     1/1     0/0     1/1     1/0     0/0     1/1     1/1
  F     0/0     1/1     1/1     1/1     1/1     0/0     1/1
  T     0/0     0/0     0/0     0/0     0/0     0/0     0/0
  T     0/1     0/1     0/0     1/1     0/1     0/0     0/1
  F     0/0     1/0     0/0     1/1     1/0     1/1     1/1
like image 912
user3354212 Avatar asked Dec 05 '25 15:12

user3354212


1 Answers

This is one way to do it with lapply that works:

#subsetting the df to just replace the elements we need
df[df$IDX==FALSE, -1] <- lapply(df[df$IDX==FALSE, -1], function(x) {
  #chartr is translates specific characters to different ones
  #here it converts 0s -> 1s and vice versa
  chartr("01", "10", x)
})

Output:

> df
    IDX  D1  D2  D3  D4  D5  D6  D7
1 FALSE 1/1 0/0 1/1 1/0 0/0 1/1 1/1
2 FALSE 0/0 1/1 1/1 1/1 1/1 0/0 1/1
3  TRUE 0/0 0/0 0/0 0/0 0/0 0/0 0/0
4  TRUE 0/1 0/1 0/0 1/1 0/1 0/0 0/1
5 FALSE 0/0 1/0 0/0 1/1 1/0 1/1 1/1
like image 137
LyzandeR Avatar answered Dec 08 '25 03:12

LyzandeR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!