R passing data.table parameters through function calls -
so if have 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 variable
fn <- "z"
i can pull column data.table following:
> dt[,fn, with=false]
what don't know how data.table equivalent of following:
> factorfunction <- function(df, fn) { df[,fn] <- as.factor(df[,fn]) return(df) }
if set fn="x" , call factorfunction(data.frame(dt),fn) works fine.
so try data.table, 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 atomic 'sort.list' have called 'sort' on list?
you can try
dt[,(fn):= factor(.sd[[1l]]),.sdcols=fn]
if there multiple columns, use lapply(.sd, factor)
wrapping in function
factorfunction <- function(df, fn) { df[, (fn):= factor(.sd[[1l]]), .sdcols=fn] } str(factorfunction(dt, fn)) #classes ‘data.table’ , 'data.frame': 4 obs. of 3 variables: #$ x: num 1 2 3 4 #$ y: chr "y" "n" "y" "m" #$ z: factor w/ 4 levels "3","8","egg",..: 4 1 2 3
Comments
Post a Comment