1
votes

Below is my data table:

DT = data.table(ID = c("a","b","c"), a=1:3, b=10:12, c=100:102)

   ID a  b   c
1:  a 1 10 100
2:  b 2 11 101
3:  c 3 12 102

I am trying to select columns a and b and renaming the selected columns to column1 and column2, respectively

DT[, .(a=column1, b=column2)]

But get the below error, not sure why. Error in eval(jsub, SDenv, parent.frame()) : object 'column1' not found

Per the documentation page for the package, I would have expected the above to work https://cran.r-project.org/web/packages/data.table/vignettes/datatable-intro.html

1
it would be other way DT[, .(column1 = a, column2 = b)], but it will only get the columns that was in side the .()' - akrun

1 Answers

1
votes

We can use setnames which will name by reference

setnames(DT, c('a', 'b'), paste0('column', 1:2))
DT
#   ID column1 column2   c
#1:  a       1      10 100
#2:  b       2      11 101
#3:  c       3      12 102

If we are selecting the column and renaming, it would be the other way i.e. instead of a = column1, it is column1 = a

DT[, .(column1 = a, column2 = b)]