Rasoul Rasoul - 1 year ago 116
R Question

convert data.frame column format from character to factor

I am programming in R language. I would like to change the format (class) of some columns of my data.frame object (

) from charactor to factor. I don't want to do this when I'm reading the text file by
function. Any help would be appreciated.

Answer Source

Hi welcome to the world of R.

mtcars  #look at this built in data set
str(mtcars) #allows you to see the classes of the variables (all numeric)

#one approach it to index with the $ sign and the as.factor function
mtcars$am <- as.factor(mtcars$am)
#another approach
mtcars[, 'cyl'] <- as.factor(mtcars[, 'cyl'])
str(mtcars)  # now look at the classes

This also works for character, dates, integers and other classes

Since you're new to R I'd suggest you have a look at these two websites:

R reference manuals: http://cran.r-project.org/manuals.html

R Reference card: http://cran.r-project.org/doc/contrib/Short-refcard.pdf

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download