I want to change a couple of data.table columns from factor to character
library(data.table)
ir <- as.data.table(iris)
ir[, Species2 := Species]
I can identify which columns I need to change
facs <- which(sapply(ir, is.factor))
facs
And I can update the columns by name:
ir[, c("Species", "Species2") := lapply(.SD, as.character), .SDcols = facs]
sapply(ir, class)
Is there a way to update the columns without referencing them by name?
You're very close. As @akrun mentioned in a comment, you can reference the columns by index, which you've obtained using which
.
ir[, which(sapply(ir, is.factor)) := lapply(.SD, as.character), .SDcols = facs]
Or even better, as @Frank mentioned in a comment, you can use parentheses.
ir[, (fac) := lapply(.SD, as.character), .SDcols = fac]
Now if you look at str(ir)
, you'll see that Species
and Species2
are now chr
rather than factor
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.