r - Update class of a subset of columns in data.table -
i want change couple of data.table columns factor character
library(data.table) ir <- as.data.table(iris) ir[, species2 := species] i can identify columns need change
facs <- which(sapply(ir, is.factor)) facs and can update columns name:
ir[, c("species", "species2") := lapply(.sd, as.character), .sdcols = facs] sapply(ir, class) is there way update columns without referencing them name?
you're close. @akrun mentioned in comment, can reference columns index, you've obtained using which.
ir[, which(sapply(ir, is.factor)) := lapply(.sd, as.character), .sdcols = facs] or better, @frank mentioned in comment, can use parentheses.
ir[, (fac) := lapply(.sd, as.character), .sdcols = fac] now if @ str(ir), you'll see species , species2 chr rather factor.
Comments
Post a Comment