+11  A: 

This was also answered in R-Help.

I imagine that there's a better way to do it, but here are two options:

# use a sample data set
> str(cars)
'data.frame':   50 obs. of  2 variables:
 $ speed: num  4 4 7 7 8 9 10 10 10 11 ...
 $ dist : num  2 10 4 22 16 10 18 26 34 17 ...
> data.df <- cars

You can use lapply:

> data.df <- data.frame(lapply(data.df, factor))

Or a for statement:

> for(i in 1:ncol(data.df)) data.df[,i] <- as.factor(data.df[,i])

In either case, you end up with what you want:

> str(data.df)
'data.frame':   50 obs. of  2 variables:
 $ speed: Factor w/ 19 levels "4","7","8","9",..: 1 1 2 2 3 4 5 5 5 6 ...
 $ dist : Factor w/ 35 levels "2","4","10","14",..: 1 3 2 9 5 3 7 11 14 6 ...
Shane
Shane,This is exactly the basic function I needed. Sorry I don't have enough reputation points to upvote it :-(
briandk
@briandk: Good to hear! At some point, just accept it so the community knows it answers your question. :)
Shane
+4  A: 

I found an alternative solution in the plyr package:

# load the package and data
> library(plyr)
> data.df <- cars

Use the colwise function:

> data.df <- colwise(factor)(data.df)
> str(data.df)
'data.frame':   50 obs. of  2 variables:
 $ speed: Factor w/ 19 levels "4","7","8","9",..: 1 1 2 2 3 4 5 5 5 6 ...
 $ dist : Factor w/ 35 levels "2","4","10","14",..: 1 3 2 9 5 3 7 11 14 6 ...

Incidentally, if you look inside the colwise function, it just uses lapply:

df <- as.data.frame(lapply(filtered, .fun, ...))
Shane
@Shane: I wish I could "accept" this one too, since it combines your lapply suggestion with some powerful features from the plyr package.
briandk