JohnnyKing
JohnnyKing

Reputation: 29

Use column names as input for formula in data.table

I want to use the column names of an data.table as an input for my formula. However, every time I insert the name of the row directly it works. If I load the name from an object, it does not work. I think it is related to the fact that

library(data.table)
  dt <- data.table(ID= c(1,2,3,4,5,6,7,8,9),
                   var1 = c(100,150,200,180,10,15,11,25,1),
                   var2 = c(150,200,250,300,15,20,19,30,2),
                   var3 = c(100,101,102,103,104,105,106,107,109))

# Insert column name direvtly in Formular seems to work
  dt[, var1 := ( var1 - mean(var1, na.rm = TRUE)/sd(var1, na.rm = TRUE)) ]

# Load name from formular does not work
  Names <- c("var1", "var2", "var3")
   for (i in 1:3){
  dt[, Names[i] := ( Names[i] - mean(Names[i], na.rm = TRUE)/sd(Names[i], na.rm = TRUE)) ]}

I think it is related to the fact that Names[1] gives me "var1" instead of var1. I was looking for similar problems in the forum and found some commands like as.symbol(), as.name() which although does not seem to help.

Upvotes: 2

Views: 1335

Answers (1)

akrun
akrun

Reputation: 887018

One option is use get to get the values from the object

for (i in 1:3){
  dt[, (Names[i]) := ( get(Names[i]) - mean(get(Names[i]),
      na.rm = TRUE)/sd(get(Names[i]), na.rm = TRUE)) ]
 }

Or another option is set

for(j in Names){
  set(dt, i = NULL, j = j, value = (dt[[j]] - mean(dt[[j]],
                    na.rm = TRUE)/sd(dt[[j]], na.rm = TRUE)))
  }
dt
#   ID         var1       var2     var3
#1:  1  99.05324836 149.060863 64.52132
#2:  2 149.05324836 199.060863 65.52132
#3:  3 199.05324836 249.060863 66.52132
#4:  4 179.05324836 299.060863 67.52132
#5:  5   9.05324836  14.060863 68.52132
#6:  6  14.05324836  19.060863 69.52132
#7:  7  10.05324836  18.060863 70.52132
#8:  8  24.05324836  29.060863 71.52132
#9:  9   0.05324836   1.060863 73.52132

Or specify the Names in .SDcols, loop through the Subset of Data.table, do the calculation and assign (;=) the output back to the columns in Names

dt[, (Names) := lapply(.SD, function(x) x- mean(x, na.rm = TRUE)/sd(x, 
                         na.rm = TRUE)), .SDcols = Names]

Upvotes: 3

Related Questions