Converting multiple data.table columns to factors in R

data.table, r

Solution

I found one solution:

library(data.table)
tst <- data.table('a' = c('b','b','c','c'))
class(tst[,a])
cols <- 'a'
tst[,(cols):=lapply(.SD, as.factor),.SDcols=cols]

Still, the earlier-mentioned behavior seems buggy.

Problem

I ran into an unexpected problem when trying to convert multiple columns of a data table into factor columns. I've reproduced it as follows: ``` library(data.table) tst <- data.table('a' = c('b','b','c','c')) class(tst[,a]) tst[,as.factor(a)] #Returns expected result tst[,as.factor('a'),with=FALSE] #Returns error ``` The latter command returns 'Error in Math.factor(j) : abs not meaningful for factors'. I found this when attempting to get tst[,lapply(cols, as.factor),with=FALSE] where cols was a collection of rows I was attempting to convert to factors. Is there any solution or workaround for this?

Original source