Chaining and link assignment in a data table.

Is it possible to combine the chain and destination by reference in the data table.

For example, I would like to do this:

DT[a == 1][b == 0, c := 2]

However, this leaves the original table unchanged, since a temporary table is created after DT [a == 1], which subsequently changes and returns.

I would rather not do

DT[a == 1 & b == 0, c := 2]

as it is very slow and i would also prefer to avoid

 DT <- DT[a == 1][b == 0, c := 2]

since I would rather do the job by reference. This question is part of the question [1], where it remains unanswered.

[1] Conditional binary connection and update by reference using the data.table package

+4
source share
1 answer

, , DT[a == 1][b == 0, c := 2] , , DT[a == 1 & b == 0, c := 2]

a b

DT <- data.table(a = c(1, 1, 1, 2, 2), b = c(0, 2, 0, 1, 1)) ## mock data
setkey(DT, a, b) ## keying by both `a` and `b`
DT[J(1, 0), c := 2] ## Update `c` by reference
DT
#    a b  c
# 1: 1 0  2
# 2: 1 0  2
# 3: 1 2 NA
# 4: 2 1 NA
# 5: 2 1 NA
+4

All Articles