so if I have a data.table defined as:
> dt <- data.table (x=c(1,2,3,4), y=c("y","n","y","m"), z=c("pickle",3,8,"egg"))
> dt
x y z
1: 1 y pickle
2: 2 n 3
3: 3 y 8
4: 4 m egg
And a variable
fn <- "z"
I get that I can pull a column from the data.table by the following:
> dt[,fn, with=FALSE]
What I don't know how to do is the data.table equivalent of the following:
> factorFunction <- function(df, fn) {
df[,fn] <- as.factor(df[,fn])
return(df)
}
If I set fn="x" and call factorFunction(data.frame(dt),fn) it works just fine.
So I try it with a data.table, but this doesn't work
> factorFunction <- function(dt, fn) {
dt[,fn, with=FALSE] <- as.factor(dt[,fn, with=FALSE])
return(dt)
}
Error in sort.list(y) : 'x' must be atomic for 'sort.list' Have you called 'sort' on a list?
dt[,fn] <- as.factor(dt[,fn, with=FALSE][[1]])
It's very close to what you've written, I think. – Frank