Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert specific numeric columns into factors?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading