[R] Grouping and Computing

Kaspar Pflugshaupt pflugshaupt at geobot.umnw.ethz.ch
Thu Feb 7 16:30:25 CET 2002


On 7.2.2002 15:03 Uhr, alexander.hener at gmx.de wrote:

> - Which object type (matrix, dataframe, list) lends itself to such a
> problem?

It's probably easiest with a dataframe, but you can also use a matrix

> - Do I have to create different objects for the groups, or can I compute the
> vector of sums directly? And how?

Do it directly, by all means. You can use any of tapply(), by() or
aggregate(): 

> testdata <- data.frame(a=factor(c(rep('a',4), rep('b',6))), b=rnorm(10))
> testdata
   a           b
1  a  0.23158790
2  a -0.38852120
    [snip]
9  b -1.81645407
10 b -0.44034004
> tapply(testdata$b, testdata$a, sum)
       a        b 
1.282057 1.511260 
> by(testdata$b,testdata$a,sum)
INDICES: a
[1] 1.282057
------------------------------------------------------------
INDICES: b
[1] 1.51126
> aggregate(testdata$b,list(testdata$a),sum)
  Group.1        x
1       a 1.282057
2       b 1.511260


See the functions' help texts and examples for further information. For me,
tapply() does all I need.

Cheers

Kaspar Pflugshaupt
 

-- 

Kaspar Pflugshaupt
Geobotanisches Institut
Zuerichbergstr. 38
CH-8044 Zuerich

Tel. ++41 1 632 43 19
Fax  ++41 1 632 12 15

mailto:pflugshaupt at geobot.umnw.ethz.ch
privat:pflugshaupt at mails.ch
http://www.geobot.umnw.ethz.ch

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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