I tried using two ways to add a column in a data.table, it returned different resuts. But I don't understand why, could you please give me a hint? Way 1:
avg_tvd <- dev_survey4[Grp==0 | Grp==1, .(avgTVD = mean(TVDmASL, na.rm=TRUE)),
by = .(Grp,WELL,APA_Pair_ID)]
Here are the results:
Way 2:
avg_tvd <- dev_survey4[Grp==0 | Grp==1, avgTVD := mean(TVDmASL, na.rm=TRUE),
by = .(Grp,WELL,APA_Pair_ID)]
Here are results:
The results of way 1 are what I want. But why way 2 has different results? There are two differences between them:
=
for aggregating/summarising, result has same number of rows as number of unique values in by
:=
for adding a column, result has the same number of rows as the original
For example:
library(data.table)
dt <- data.table(I = 1:3, x = 11:13, y = c("A", "A", "B"))
dt[, .(mx = mean(x)), by = "y"]
#> y mx
#> 1: A 11.5
#> 2: B 13.0
dt[, mx := mean(x), by = "y"][]
#> I x y mx
#> 1: 1 11 A 11.5
#> 2: 2 12 A 11.5
#> 3: 3 13 B 13.0
Created on 2018-06-16 by the reprex package (v0.2.0).