lizzie
lizzie

Reputation: 606

Replace values in a subset of a data.table

Let's suppose I have this:

dt <- data.table(mtcars)[1:3, ]
dt[wt == 2.620, "am"] <- 4
dt[wt == 2.620,]

My output is:

    mpg cyl disp  hp drat   wt  qsec vs am gear carb
1:  21   6  160 110  3.9 2.62 16.46  0  4    4    4

I want to replace the value 4 by 0 only in the columns gear and carb.

The final data would look like this:

    mpg cyl disp  hp drat    wt  qsec vs am gear carb
1: 21.0   6  160 110 3.90 2.620 16.46  0  4    0    0
2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

Upvotes: 2

Views: 3704

Answers (2)

SymbolixAU
SymbolixAU

Reputation: 26248

In your small example, the method proposed by @HenryRice is sufficient (with maybe a further subset where wt == 2.62).

If you were doing it on more rows or columns, using data.table's for / set loop would be useful in this scenario

for(j in c("gear", "carb"))
    set(dt, i = which(dt[[j]] == 4 & dt[["wt"]] == 2.620), j = j, value = 0)

dt
#     mpg cyl disp  hp drat    wt  qsec vs am gear carb
# 1: 21.0   6  160 110 3.90 2.620 16.46  0  4    0    0
# 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

Upvotes: 4

Mako212
Mako212

Reputation: 7292

Like this:

dt$carb[dt$carb==4] <- 0
dt$gear[dt$gear==4] <- 0

Upvotes: -1

Related Questions