1

I am trying to modify a dataframe by converting multiple integer variables to factors.

A simple dataframe for illustrative purposes is the following:

mydf<-data.frame(x=1:10, y=11:20, z=21:30)

Let's say I would like to change the first two columns from int to factor. In order to achieve this I could write

mydf[,1] <- as.factor(mydf[,1])
mydf[,2] <- as.factor(mydf[,2])

This piece code works but if I have to change many columns, I will have to repeat this piece of code many times. I have tried

mydf[,c(1,2)]<-as.factor(mydf[,c(1,2)])

but the output is

str(mydf)
'data.frame':   10 obs. of  3 variables:
$ x: chr  "1:10" "11:20" "1:10" "11:20" ...
$ y: chr  "1:10" "11:20" "1:10" "11:20" ...
$ z: int  21 22 23 24 25 26 27 28 29 30

How can I achieve my target in a more elegant and neat way? Thanks!

DanY
  • 5,920
  • 1
  • 13
  • 33
Marco De Virgilis
  • 982
  • 1
  • 9
  • 29

0 Answers0