<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
Kevin Murphy wrote:
<blockquote TYPE=CITE>I would like to specify that certain columns in a
data frame should be
<br>treated as ordered factors. I know what numbers these columns are,
but
<br>not their names.
<br>How do I do this?
<p>For example, if I know columns 1:4 are to be treated as factors, I can
<br>write
<p>dat <- matrix(c(2,1,1,1, 1,1,1,1), 2, 4)
<br>D <- as.data.frame(dat)
<br># force all variables to be treated as binary
<br># regardless of the small data set
<br>D$V1 <- factor(D$V1, 1:2)
<br>D$V2 <- factor(D$V2, 1:2)
<br>D$V3 <- factor(D$V3, 1:2)
<br>D$V4 <- factor(D$V4, 1:2)
<p>But how do I do this in general? What I would like to say is something
<br>like
<p>for (i in my.factor.columns) {
<br> D$Vi <- factor(D$Vi, 1:my.nlevels[i])
<br>}
<p>Presumably I could do something tricky using eval, but I don't know
how.
<br>Besides, I'd prefer to avoid eval, since it is slow.
<br>(Also, I don't want to rely on the fact that the columns are named
"Vnn"
<br>by default.)
<p>Kevin</blockquote>
<br>
<br>
<br>
<br>
<p>What about:
<p>> dat <- matrix(c(2,1,1,1, 1,1,1,1), 2, 4)
<br>> D <- as.data.frame(dat)
<br>> makefactor <- function(d,index) { d[index] <- sapply(d[index],factor);
return(d) }
<br>> # say one wants the two first columns to be factors
<br>> index <- c(1,2)
<br>> str(makefactor(D,index))
<br>
<br>
<p>Regards,
<br>
<br>
<p>Laurent
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<blockquote TYPE=CITE>
<br>-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
<br>r-help mailing list -- Read <a href="http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html">http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html</a>
<br>Send "info", "help", or "[un]subscribe"
<br>(in the "body", not the subject !) To: r-help-request@stat.math.ethz.ch
<br>_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._</blockquote>
<pre>--
Laurent Gautier CBS, Building 208, DTU
PhD. Student D-2800 Lyngby,Denmark
tel: +45 45 25 24 85 <A HREF="http://www.cbs.dtu.dk/laurent">http://www.cbs.dtu.dk/laurent</A></pre>
</html>