Lin Yang
Lin Yang

Reputation: 45

R data.table, How to add 1 to each cell value is not equal to 0

I have binary R data.frame, the 1st column is ID. How do I add 1 to these non-zero values?

id      A   B  C
001     0   1  0
002     0   0  1

Should become

id      A   B  C
001     0   2  0
002     0   0  2

Upvotes: 2

Views: 571

Answers (4)

Ronak Shah
Ronak Shah

Reputation: 389325

Since you have a binary data you can add the data with itself so 0 + 0 remains 0 and 1 + 1 will become 2. Ignoring the first id column of course.

df[-1] <- df[-1] + df[-1]
df
#   id A B C
#1 001 0 2 0
#2 002 0 0 2

Upvotes: 0

r2evans
r2evans

Reputation: 161085

While I suspect the other answers will suffice, you mentioned data.table in the question title, so here's one specific to that package:

library(data.table)
DT <- fread(header = TRUE, text = "
id      A   B  C
001     0   1  0
002     0   0  1", colClasses = list(character="id"))

sdcols <- c("A", "B", "C")
DT[, (sdcols) := .SD + (.SD != 0), .SDcols = sdcols]
DT
#     id A B C
# 1: 001 0 2 0
# 2: 002 0 0 2

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102770

Since you can treat the zeros as the mask, you are able to play some tricks like below

df[-1] <- df[-1]*(df[-1]+1)

Upvotes: 1

akrun
akrun

Reputation: 887951

We can multiply by the number wanted which makes use of the 0 multipled by any value returns 0

df1[-1] <- df1[-1] * 2

Or an option is to create a logical matrix on the subset of columns, use that to subset the values and assign the number

df1[-1][df1[-1] ==1] <- 2

Or add

df1[-1][df1[-1] ==1] <- df1[-1][df1[-1] ==1] + 1

Upvotes: 2

Related Questions