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
2009-09-28 20:41:18