[R] Summing rows by years (each time separately)

William Dunlap wdunlap at tibco.com
Mon Jan 9 02:43:33 CET 2012


In aggregate() you can use the following as your
grouping ('by') variable
   group <- cumsum(c(TRUE, year[-1] != y[-length(year)]))
where 'year' is the column of your matrix containing
the 2008, 2009, ...

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of David Winsemius
> Sent: Sunday, January 08, 2012 5:36 PM
> To: Andrew Gaska
> Cc: r-help at r-project.org
> Subject: Re: [R] Summing rows by years (each time separately)
> 
> 
> On Jan 8, 2012, at 1:57 PM, Andrew Gaska wrote:
> 
> > Dear all,
> >
> > I could not find an answer for the problem.
> >
> > I have a matrix and I want to sum rows in groups i.e. rows are
> > summed as
> > long as rows of column 1 have some value (f.e. 2008 in it), then
> > again rows
> > are summed as long as rows of column 2 have some value (f.e. 2009 in
> > it).
> >
> 
> ?aggregate
> 
> --
> David.
> > In case there is a repetition of value in column 1 in another group,
> > this
> > group should be summed seperately.
> >
> > Example:
> >
> > I have such a matrix:
> >
> > *1.2008*	3	2	2
> > *2.2008*	4	3	3
> > * 3.2008*	5	4	4
> > * 4.2008*	3	3	1
> > *1.2009*	6	1	2
> > *2.2009*	3	2	5
> > *1.2010*	4	4	3
> > * 2.2010*	3	3	2
> > *3.2010*	1	5	3
> > *4.2010*	2	2	2
> > * 1.2008*	3	1	1
> > *2.2008*	4	3	2
> > *3.2008*	2	4	3
> > *1.2009*	1	2	4
> > *2.2009*	5	4	3
> > *3.2009*	4	3	3
> > *1.2010*	4	3	1
> > *2.2010*	2	2	2
> >
> > The result should be like this:
> >
> > *2008*	15	12	10
> > *2009*	9	3	7
> > *2010*	10	14	10
> > *2008*	9	8	6
> > *2009*	10	9	10
> > *2010*	6	5	3
> >
> >
> > Could You help me with that?
> >
> > Yours,
> > Andrew Gaska
> >
> >
> > --
> > View this message in context: http://r.789695.n4.nabble.com/Summing-rows-by-years-each-time-
> separately-tp4276428p4276428.html
> > Sent from the R help mailing list archive at Nabble.com.
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> 
> David Winsemius, MD
> West Hartford, CT
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list