[R] subtotal for same row data

Petr Pikal petr.pikal at precheza.cz
Mon Mar 26 07:07:14 CEST 2007


Hi

Or perhaps aggregate

> aggregate(x$F, list(C1=x$C1, C2=x$C2), sum)
  C1 C2   x
1  1  2 0.5
2  2  2 0.5

Regards
Petr


On 23 Mar 2007 at 16:13, jim holtman wrote:

Date sent:      	Fri, 23 Mar 2007 16:13:30 -0400
From:           	"jim holtman" <jholtman at gmail.com>
To:             	"Yuan, Qiaoping (NIH/NIAAA) [E]" <qyuan at mail.nih.gov>
Copies to:      	r-help at stat.math.ethz.ch
Subject:        	Re: [R] subtotal for same row data

> try this:
> 
> > x <- as.data.frame(x)
> > x
>    C1 C2 C3   F
> R1  1  2  2 0.3
> R2  2  2  2 0.5
> R3  1  2  1 0.2
> > do.call('rbind',by(x, list(x$C1, x$C2), function(z){z$F <- sum(z$F);
> z[1,]}))
>    C1 C2 C3   F
> R1  1  2  2 0.5
> R2  2  2  2 0.5
> >
> 
> 
> 
> On 3/23/07, Yuan, Qiaoping (NIH/NIAAA) [E] <qyuan at mail.nih.gov> wrote:
> > > Hi, There, > > I would like to subtotal the number in a specified
> column for all rows > having the same data for specified columns. The
> following is the simple > example: > > > >
> x=matrix(c(1,2,2,0.3,2,2,2,0.5,1,2,1,0.2),3,4,byrow=T) > >
> rownames(x)=c("R1","R2","R3") > > colnames(x)=c("C1","C2","C3","F") >
> > x > C1 C2 C3 F > R1 1 2 2 0.3 > R2 2 2 2 0.5 > R3 1 2 1 0.2 > > I
> would like to get the subtotal in column "F" based on same row data in
> > column "C1" and "C2". The result should be like > > C1   C2     SumF
> > 1 2 0.5 # This is 0.3 + 0.2 from R1 and R3 > 2 2 0.5 > > Is there a
> simple way to do this? Any help will be greatly appreciated. > >
> Qiaoping Yuan > > ______________________________________________ >
> R-help at stat.math.ethz.ch 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. >
> 
> 
> 
> -- 
> Jim Holtman
> Cincinnati, OH
> +1 513 646 9390
> 
> What is the problem you are trying to solve?
> 
>  [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.

Petr Pikal
petr.pikal at precheza.cz



More information about the R-help mailing list