I would like to modify a set of columns inside a data.table to be factors. If I knew the names of the columns in advance, I think this would be straightforward.
library(data.table)
dt1 <- data.table(a = (1:4), b = rep(c('a','b')), c = rep(c(0,1)))
dt1[,class(b)]
dt1[,b:=factor(b)]
dt1[,class(b)]
But I don't, and instead have a list of the variable names
vars.factors <- c('b','c')
I can apply the factor function to them without a problem ...
lapply(vars.factors, function(x) dt1[,class(get(x))])
lapply(vars.factors, function(x) dt1[,factor(get(x))])
lapply(vars.factors, function(x) dt1[,factor(get(x))])
But I don't know how to re-assign or update the original column in the data table.
This fails ...
lapply(vars.factors, function(x) dt1[,x:=factor(get(x))])
# Error in get(x) : invalid first argument
As does this ...
lapply(vars.factors, function(x) dt1[,get(x):=factor(get(x))])
# Error in get(x) : object 'b' not found
NB. I tried the answer proposed here without any luck.