<!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 &lt;- matrix(c(2,1,1,1, 1,1,1,1), 2, 4)
<br>D &lt;- as.data.frame(dat)
<br># force all variables to be treated as binary
<br># regardless of the small data set
<br>D$V1 &lt;- factor(D$V1, 1:2)
<br>D$V2 &lt;- factor(D$V2, 1:2)
<br>D$V3 &lt;- factor(D$V3, 1:2)
<br>D$V4 &lt;- 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>&nbsp; D$Vi &lt;- 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>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<p>What about:
<p>> dat &lt;- matrix(c(2,1,1,1, 1,1,1,1), 2, 4)
<br>> D &lt;- as.data.frame(dat)
<br>> makefactor &lt;- function(d,index) { d[index] &lt;- sapply(d[index],factor);
return(d) }
<br>> # say one wants the two first columns to be factors
<br>> index &lt;- c(1,2)
<br>> str(makefactor(D,index))
<br>&nbsp;
<br>&nbsp;
<p>Regards,
<br>&nbsp;
<br>&nbsp;
<p>Laurent
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<br>&nbsp;
<blockquote TYPE=CITE>&nbsp;
<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 !)&nbsp; To: r-help-request@stat.math.ethz.ch
<br>_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._</blockquote>

<pre>--&nbsp;
Laurent Gautier&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CBS, Building 208, DTU
PhD. Student&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; D-2800 Lyngby,Denmark&nbsp;&nbsp;&nbsp;
tel: +45 45 25 24 85&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="http://www.cbs.dtu.dk/laurent">http://www.cbs.dtu.dk/laurent</A></pre>
&nbsp;</html>