(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 his blog: theBioBucket*.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).