convert data frame column to factor
15,288
Solution 1
apply
is usually not suitable for data.frames, because it returns a matrix. You could use lapply
instead:
yy <- data.frame(lapply(xx, as.factor))
str(yy)
#'data.frame': 4 obs. of 2 variables:
# $ aa: Factor w/ 4 levels "1","2","3","4": 1 2 3 4
# $ bb: Factor w/ 4 levels "6","7","8","9": 1 2 3 4
I assume you realize you could also just do
xx <- data.frame(aa = as.factor(aa), bb = as.factor(bb))
Solution 2
I would do something like:
library(dplyr)
yy = xx %>% mutate_each(funs(as.factor))
This applies as.factor
to each column in xx
.
Author by
Apostolos
Updated on August 02, 2022Comments
-
Apostolos over 1 year
I want just to convert two columns of a data frame to factors. I use the apply function but the result is characters, not factors. Any idea what I am doing wrong ?
aa <- c(1,2,3,4) bb <- c(6,7,8,9) xx <- data.frame(aa, bb) xx yy <- apply(xx, 2, function(xx) as.factor(xx)) # aa bb # [1,] "1" "6" # [2,] "2" "7" # [3,] "3" "8" # [4,] "4" "9"
When I am implementing the same to a stand alone vector, it works:
nn <- c(1,2,3,4) mm <- as.factor(nn) mm