I'm trying to turn some of the variables in my data.frame
into factor
while preserving the data.frame structure. I follow the suggestions HERE but I don't get my desired output, any fix?
d <- data.frame(a = c(1,2, 3, 5), b = c(2,3, 4, 2), e = c(3,4,5,1), f = rep(c("long", "short"), 2))
factor.name <- names(d)[-4]
d[] <- lapply(seq_along(factor.name), function(i) as.factor(d[factor.name[i]]))
Subset the data with 'factor.name', pass that in lapply
and update the columns
d[factor.name] <- lapply(d[factor.name], factor)
library(dplyr)
d <-
d %>%
mutate_at(vars(a, b, e), as.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.