Update class of subset of columns in data.table
I want to change a couple of columns of data.table from coefficient to character
library(data.table)
ir <- as.data.table(iris)
ir[, Species2 := Species]
I can determine which columns I need to change
facs <- which(sapply(ir, is.factor))
facs
And I can update columns by name:
ir[, c("Species", "Species2") := lapply(.SD, as.character), .SDcols = facs]
sapply(ir, class)
Is there a way to update columns without referring to them by name?
source to share
You are very close. As @akrun pointed out in the comment, you can refer to columns by index you got with which
.
ir[, which(sapply(ir, is.factor)) := lapply(.SD, as.character), .SDcols = facs]
Or even better, as @Frank pointed out in the comment, you can use parentheses.
ir[, (fac) := lapply(.SD, as.character), .SDcols = fac]
Now, if you look str(ir)
, you'll see that Species
and Species2
are now chr
instead factor
.
source to share