Note that there are some explanatory texts on larger screens.

plurals
  1. POquick/elegant way to construct mean/variance summary table
    primarykey
    data
    text
    <p>I can achieve this task, but I feel like there must be a "best" (slickest, most compact, clearest-code, fastest?) way of doing it and have not figured it out so far ...</p> <p>For a specified set of categorical factors I want to construct a table of means and variances by group.</p> <p><strong>generate data</strong>:</p> <pre><code>set.seed(1001) d &lt;- expand.grid(f1=LETTERS[1:3],f2=letters[1:3], f3=factor(as.character(as.roman(1:3))),rep=1:4) d$y &lt;- runif(nrow(d)) d$z &lt;- rnorm(nrow(d)) </code></pre> <p><strong>desired output</strong>:</p> <pre><code> f1 f2 f3 y.mean y.var 1 A a I 0.6502307 0.09537958 2 A a II 0.4876630 0.11079670 3 A a III 0.3102926 0.20280568 4 A b I 0.3914084 0.05869310 5 A b II 0.5257355 0.21863126 6 A b III 0.3356860 0.07943314 ... etc. ... </code></pre> <p><strong>using <code>aggregate</code>/<code>merge</code>:</strong></p> <pre><code>library(reshape) m1 &lt;- aggregate(y~f1*f2*f3,data=d,FUN=mean) m2 &lt;- aggregate(y~f1*f2*f3,data=d,FUN=var) mvtab &lt;- merge(rename(m1,c(y="y.mean")), rename(m2,c(y="y.var"))) </code></pre> <p><strong>using <code>ddply</code>/<code>summarise</code></strong> (possibly best but haven't been able to make it work):</p> <pre><code>mvtab2 &lt;- ddply(subset(d,select=-c(z,rep)), .(f1,f2,f3), summarise,numcolwise(mean),numcolwise(var)) </code></pre> <p>results in</p> <pre><code>Error in output[[var]][rng] &lt;- df[[var]] : incompatible types (from closure to logical) in subassignment type fix </code></pre> <p><strong>using <code>melt</code>/<code>cast</code></strong> (maybe best?)</p> <pre><code>mvtab3 &lt;- cast(melt(subset(d,select=-c(z,rep)), id.vars=1:3), ...~.,fun.aggregate=c(mean,var)) ## now have to drop "variable" mvtab3 &lt;- subset(mvtab3,select=-variable) ## also should rename response variables </code></pre> <p>Won't (?) work in <code>reshape2</code>. Explaining <code>...~.</code> to someone could be tricky!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload