in data.table, assign multiple columns by reference in r

To assign multiple columns by reference in data.table, you can use the := operator and list the columns to be assigned as new values. Here's an example:

main.r
library(data.table)

# create a sample data.table
dt <- data.table(x = 1:5, y = c("a", "b", "c", "d", "e"), z = 6:10)
dt
#>    x y  z
#> 1: 1 a  6
#> 2: 2 b  7
#> 3: 3 c  8
#> 4: 4 d  9
#> 5: 5 e 10

# assign new values to multiple columns by reference
dt[, c("x", "z") := list(x * 2, z + 1)]
dt
#>     x y  z
#> 1:  2 a  7
#> 2:  4 b  8
#> 3:  6 c  9
#> 4:  8 d 10
#> 5: 10 e 11
380 chars
22 lines

In the above example, we first created a data.table called dt and then used the := operator to assign new values to columns x and z by multiplying x by 2 and adding 1 to z. We did this all by reference, without creating a copy of the original data.table.

gistlibby LogSnag