[R] variable number of variables in data frames

Kevin Murphy murphyk at cs.berkeley.edu
Tue Jul 17 03:18:32 CEST 2001

I would like to specify that certain columns in a data frame should be
treated as ordered factors. I know what numbers these columns are, but
not their names.
How do I do this?

For example, if I know columns 1:4 are to be treated as factors, I can

dat <- matrix(c(2,1,1,1, 1,1,1,1), 2, 4)
D <- as.data.frame(dat)
# force all variables to be treated as binary
# regardless of the small data set
D$V1 <- factor(D$V1, 1:2)
D$V2 <- factor(D$V2, 1:2)
D$V3 <- factor(D$V3, 1:2)
D$V4 <- factor(D$V4, 1:2)

But how do I do this in general? What I would like to say is something

for (i in my.factor.columns) {
  D$Vi <- factor(D$Vi, 1:my.nlevels[i])

Presumably I could do something tricky using eval, but I don't know how.
Besides, I'd prefer to avoid eval, since it is slow.
(Also, I don't want to rely on the fact that the columns are named "Vnn"
by default.)

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list