user3354212
user3354212

Reputation: 1112

Swap values across multiple columns by a condition

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

Upvotes: 3

Views: 273

Answers (2)

Ven Yao
Ven Yao

Reputation: 3710

Not using lapply.

df[df$IDX==FALSE, -1] <- chartr("01", "10", as.matrix(df[df$IDX==FALSE, -1]))
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

Upvotes: 0

LyzandeR
LyzandeR

Reputation: 37889

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

Upvotes: 5

Related Questions