Search code examples
rdata.tableassignment-operatorcolon-equals

Adding a column in data.table with = vs :=


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:

enter image description here

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:

enter image description here

The results of way 1 are what I want. But why way 2 has different results? There are two differences between them:

  1. Columns of ways 2 are more than way 1;
  2. Row of way 2 has Grps besides 0 and 1.

Solution

  • = 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).