Home > front end >  How to convert specific numeric columns into factors?
How to convert specific numeric columns into factors?

Time:10-10

I have this dataframe :

df <- data.frame(identifiant=c(11, 12, 13, 14, 15),  
                  x=c(1, 2, 3, 4, 5),  
                  y=c(1, 2, 3, 4, 5))

and I wish only the second and the third columns to become ordered factors.

Thanks.

CodePudding user response:

You can use this approach.

tof <- c('x', 'y')

df[tof] <- lapply(df[tof], as.factor)
str(df)
# 'data.frame': 5 obs. of  3 variables:
# $ identifiant: num  11 12 13 14 15
# $ x          : Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5
# $ y          : Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5

I you really want ordered factors, do

df[tof] <- lapply(df[tof], factor, ordered=TRUE)
str(df)
# 'data.frame': 5 obs. of  3 variables:
# $ identifiant: num  11 12 13 14 15
# $ x          : Ord.factor w/ 5 levels "1"<"2"<"3"<"4"<..: 1 2 3 4 5
# $ y          : Ord.factor w/ 5 levels "1"<"2"<"3"<"4"<..: 1 2 3 4 5
  • Related