Skip to content

Question on summing rows within nested variable

3 messages · Vedula, Satyanarayana, David Winsemius, jim holtman

#
DF2 <- read.table(textConnection("sid        pid        slope
+ 1.1        1.1        2
+ 1.1        4.1        3
+ 1.1        5.1        2
+ 2.1        5.1        3
+ 3.2        1.2        2
+ 3.2        1.7        3"), header = TRUE)


 > tapply(DF2$slope, as.factor(DF2$pid), mean)
1.1 1.2 1.7 4.1 5.1
2.0 2.0 3.0 3.0 2.5

Could also wrap it in with(DF2, ....)  to make it more readable and  
compact. As testing shows that the as.factor() is not needed.
#
If you want zero if only one variable:
sid pid slope
1 1.1 1.1     2
2 1.1 4.1     3
3 1.1 5.1     2
4 2.1 5.1     3
5 3.2 1.2     2
6 3.2 1.7     3
1.1      2.1      3.2
2.333333 0.000000 2.500000
On Fri, Mar 13, 2009 at 6:43 PM, Vedula, Satyanarayana
<svedula at jhsph.edu> wrote: