Try:
DT = data.table(col1 = 1:3) colname = "col1" DT[, colname, with = FALSE] # select # col1 # 1: 1 # 2: 2 # 3: 3 DT[, (colname) := 4:6] # assign # col1 # 1: 4 # 2: 5 # 3: 6
The latter is known as the plonk column, because you replace the entire column vector with a link. If there is a subset i , it will reassign by reference. Paranas around (colname) is a shorthand introduced in version v1.9.4 on CRAN Oct 2014. Here's the news:
Using `with = FALSE` with `:=` is now deprecated in all cases, given that wrapping the LHS of `:=` with parentheses has been preferred for some time. colVar = "col1" DT[, colVar := 1, with = FALSE] # deprecated, still works silently DT[, (colVar) := 1] # please change to this DT[, c("col1", "col2") := 1] # no change DT[, 2:4 := 1] # no change DT[, c("col1","col2") := list(sum(a), mean(b)] # no change DT[, `:=`(...), by = ...] # no change
See also the Details section in ?`:=` :
DT[i, (colnamevector) := value]
And to answer the next question in a comment, here is one way (as usual, there are many ways):
DT[, colname := cumsum(get(colname)), with = FALSE]
or it may be easier for you to read, write, and debug only up to eval a paste , like building a dynamic SQL statement to send to the server:
expr = paste0("DT[,",colname,":=cumsum(",colname,")]") expr # [1] "DT[,col1:=cumsum(col1)]" eval(parse(text=expr)) # col1 # 1: 4 # 2: 13 # 3: 28
If you do so much, you can define an auxiliary function eval :
EVAL = function(...)eval(parse(text=paste0(...)),envir=parent.frame(2)) EVAL("DT[,",colname,":=cumsum(",colname,")]") # col1 # 1: 4 # 2: 17 # 3: 45
Now that data.table 1.8.2 automatically optimizes j for efficiency, it may be preferable to use the eval method. get() in j prevents some optimizations, for example.
Or there is set() . Low service, functional form := , which would be nice. See ?set .
set(DT, j = colname, value = cumsum(DT[[colname]])) DT # col1 # 1: 4 # 2: 21 # 3: 66