Say I have the following data.table
dt <- data.table(var = c("a", "b"), val = c(1, 2))
Now I want to add two new columns to dt, named a, and b with the respective values (1, 2). I can do this with a loop, but I want to do it the data.table way.
The result would be a data.table like this:
dt.res <- data.table(var = c("a", "b"), val = c(1, 2), #old vars
a = c(1, NA), b = c(NA, 2)) # newly created vars
So far I came up with something like this
dt[, c(xx) := val, by = var]
where xx would be a data.table-command similar to .N which addresses the value of the by-group.
Thanks for the help!
Appendix: The for-loop way
The non-data.table-way with a for-loop instead of a by-argument would look something like this:
for (varname in dt$var){
dt[var == varname, c(varname) := val]
}
dt[, c('a', 'b') := Map('*', lapply(var, function(x) val[NA^(x!=var)]), val)]- akrundt[, ':='(var1=val1, var2=val2...) ]? Do you need to generate or pass the names programmatically? - smcixxwould be a data.table-command similar to.Nwhich addresses the value of the by-group". Can you give an example? Do you want to form the variable name vector in xx based on the names in the by-argument? Please give an example. - smci