[R] manipulate group data using column name
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Feb 8 17:41:07 CET 2007
Try this:
fa$sum <- ave(fa$X1, fa$X3, FUN = sum)
On 2/8/07, sun <flyhyena at yahoo.com> wrote:
> Hi,
>
> Maybe this is a trivial question but I can not figure out a good solution.
>
> I have a data frame fa and want to add a new column "sum" with the sum value
> of fa$X1 grouped by fa$X3.
>
> > fa
> X1 X2 X3
> 1 1 11 1
> 2 2 12 1
> 3 3 13 1
> 4 4 14 2
> 5 5 15 2
> 6 6 16 2
> 7 7 17 3
> 8 8 18 3
> 9 9 19 3
> 10 10 20 3
>
> fa$X3 is the index of group
>
> i can
>
> >aggregate(fa[,"X1"],list(fa$X3),sum)
> Group.1 x
> 1 1 6
> 2 2 15
> 3 3 34
>
> then I want to add a new column "sum" in fa and assign the aggregated result
> to the new column. Is there a solution without using loops?
> or maybe there is some way can even avoid aggregate operation?
>
> Thanks.
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list