adding column to data.table while modifying

While working with data.table I wish to add a new column and assign that to a variable. For example an operation like this:

library(data.table)

x = data.table(col1 = rnorm(10), col2 = rnorm(10))
y = x[, .(col3 = rnorm(10))]
y
#>           col3
#>  1:  0.3896814
#>  2: -0.9697096
#>  3: -0.8036384
#>  4:  2.7868096
#>  5: -0.6685163
#>  6:  1.1313373
#>  7:  1.7167572
#>  8: -0.9787288
#>  9: -0.4564597
#> 10:  0.4010645

Created on 2021-07-22 by the reprex package (v2.0.0)

As you can see in the above example, y just returned the col3 but I wish to retain the col1 and col2 as well while assigning but not change x i.e. y should have col1, col2 and col3 but x should only have col1 and col2. I know, I can use := operator but that modifies the original table as well.

I know I can achieve this by calling copy() but wondering if there is a way to avoid this extra step:

library(data.table)

x = data.table(col1 = rnorm(10), col2 = rnorm(10))

# adding a new column to y without modifying x

y = copy(x)
y$col3 = rnorm(10)

y
#>            col1       col2       col3
#>  1:  0.17515821  0.1176021 -0.1347739
#>  2:  2.20399094 -1.7367777 -1.1524410
#>  3: -1.40434275 -1.1361914 -1.8311661
#>  4: -0.49387179 -2.1259718 -1.3750332
#>  5:  1.46795492  0.3063904 -0.5809118
#>  6:  0.64698082  0.5736446 -0.5618565
#>  7:  1.29720045 -0.3974435  1.9326449
#>  8:  0.17654267  1.8410662 -0.3044560
#>  9:  0.03544842 -0.1519397  1.1844237
#> 10: -0.90924160 -1.9819158  1.5297478

Created on 2021-07-22 by the reprex package (v2.0.0)

Thanks a lot for your help and time.



Read more here: https://stackoverflow.com/questions/68480686/adding-column-to-data-table-while-modifying

Content Attribution

This content was originally published by monte at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: