Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new column in a data.table when the name of column must be a string [duplicate]

Tags:

r

data.table

How to create new column in a data.table when the name of column must be a string or character?

For example:

library(data.table)
DT = data.table(v1=c(1,2,3), v2=2:4)
new_var <- "v3"
DT[, new_var:=v2+5]

I Get

DT
#>    v1 v2 new_var
#> 1:  1  2       7
#> 2:  2  3       8
#> 3:  3  4       9

But, I want

#>    v1 v2      v3
#> 1:  1  2       7
#> 2:  2  3       8
#> 3:  3  4       9
like image 572
Selva Avatar asked Oct 17 '25 10:10

Selva


1 Answers

I can be done this way, by enclosing the variable name within brackets:

DT = data.table(v1=c(1,2,3), v2=2:4)
new_var <- "v3"
DT[, eval(new_var):=v2+5]
# or
DT[, (new_var):=v2+5]
DT
#>    v1 v2      v3
#> 1:  1  2       7
#> 2:  2  3       8
#> 3:  3  4       9
like image 102
Selva Avatar answered Oct 20 '25 00:10

Selva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!