Is it possible to directly read CSV columns as categorical data?

I need to analyze with R the data from a medical survey (with 100+ coded columns) that comes in a CSV. I will use rattle for some initial analysis but behind the scenes it's still R.

If I read.csv() the file, columns with numerical codes are treated as numerical data. I'm aware I could create categorical columns from them with factor() but doing it for 100+ columns is a pain.

I hope there is a better way to tell R to import the columns directly as factors. Or to at least to convert them in place afterwards.

Thank you!

-
We're happy to take R questions here. See meta.stats.stackexchange.com/questions/252/… – Rob Hyndman Aug 10 '10 at 1:22

You can use the colClasses argument to specify the classes of your data columns. For example:

data <- read.csv('foo.csv', colClasses=c('numeric', 'factor', 'factor'))


will assign numeric to the first column, factor to the second and third. Since you have so many columns, a shortcut might be:

data <- read.csv('foo.csv', colClasses=c('numeric', rep('factor', 37), 'character'))


or some such variation (i.e. assign numeric to first column, factor to next 37 columns, then character to the last one).

-

or just do it after you read the data

dat <- read.csv("kdfjdkf")
apply(dat, 2, factor)


though this type of Q is probably more fit for Stack Overflow.

edit: see below.

-
 See meta.stats.stackexchange.com/questions/252/… the current consensus is that this is an appropriate question, if you disagree chime in at meta, don't torment the new question asker. – Russell S. Pierce Aug 9 '10 at 22:53 ok, but you'll probably have a bigger audience to get responses for a pure R question (at least for now) -- hence, the "probably". "torment" is a strong word eh? :) – apeescape Aug 9 '10 at 23:51 Sure, torment is a bit strong; I'm sorry about that. I was/am just frustrated with repeat offender users (of which you are not one) who persist in redirecting question askers to StackOverflow without having made any comment on meta (where the consensus seems pretty clear). – Russell S. Pierce Aug 10 '10 at 0:15