1

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]]))

2 Answers2

2

Subset the data with 'factor.name', pass that in lapply and update the columns

d[factor.name] <- lapply(d[factor.name], factor)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Code could be cleaned up by eliminating the creation of `factor.name` with `d[,1:3] <- lapply(d[,1:3], factor)`. – LouisMP Oct 31 '19 at 17:53
  • 1
    @LouisPenrod I guess the OP's `factor.name` vector would be passed on from another function or so – akrun Oct 31 '19 at 17:55
1
library(dplyr)
d <-
  d %>% 
  mutate_at(vars(a, b, e), as.factor)
Iaroslav Domin
  • 2,698
  • 10
  • 19