# Conversion of Several Variables to Factors

December 15, 2011
By

(This article was first published on theBioBucket*, and kindly contributed to R-bloggers)

..often needed when preparing data for analysis (and usually forgotten until I need it for the next time).
With the below code I convert a set of variables to factors – it could be that there are slicker ways to do it (if you know one let me know!)

`> dat <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))> str(dat)'data.frame':   4 obs. of  10 variables: \$ A: int  5 34 3 15 \$ B: int  28 25 17 24 \$ C: int  2 12 10 32 \$ D: int  16 27 29 14 \$ E: int  40 7 4 31 \$ F: int  22 30 6 18 \$ G: int  33 36 35 38 \$ H: int  19 21 37 8 \$ I: int  20 11 9 26 \$ J: int  39 13 1 23> > id <- which(names(dat)%in%c("A", "F", "I"))> dat[, id] <- lapply(dat[, id], as.factor)> str(dat[, id])'data.frame':   4 obs. of  3 variables: \$ A: Factor w/ 4 levels "3","5","15","34": 2 4 1 3 \$ F: Factor w/ 4 levels "6","18","22",..: 3 4 1 2 \$ I: Factor w/ 4 levels "9","11","20",..: 3 2 1 4`

To leave a comment for the author, please follow the link and comment on their blog: theBioBucket*.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.

## Sponsors

Contact us if you wish to help support R-bloggers, and place your banner here.

# Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts.(You will not see this message again.)

Click here to close (This popup will not appear again)