Re: [R] Adding columns of Aggregates to existing dataframe

From: jim holtman <jholtman_at_gmail.com>
Date: Sat, 21 Jun 2008 14:43:54 -0400

This should do it for you:

> x <- read.table(textConnection("ID1 ID2

+ A1    B3
+ A1    B4
+ A1    B3
+ A1    B3
+ A2    B1
+ A2    B1
+ A2    B4
+ A3    B2
+ A3    B2
+ A5    B1
+ A5    B1
+ A5    B6
+ A5    B4
+ A6    B2"), header=TRUE)

> cbind(x, countID1=ave(seq_along(x$ID1), x$ID1, FUN=length),
+ countID2=ave(seq_along(x$ID2), x$ID2, FUN=length)) ID1 ID2 countID1 countID2 1 A1 B3 4 3 2 A1 B4 4 3 3 A1 B3 4 3 4 A1 B3 4 3 5 A2 B1 3 4 6 A2 B1 3 4 7 A2 B4 3 3 8 A3 B2 2 3 9 A3 B2 2 3 10 A5 B1 4 4 11 A5 B1 4 4 12 A5 B6 4 1 13 A5 B4 4 3 14 A6 B2 1 3

On Fri, Jun 20, 2008 at 9:04 PM, tonyxv <tonyxv_at_gmail.com> wrote:
>
> Hello,
> I have a dataframe
>
>
> ID1 ID2
> A1 B3
> A1 B4
> A1 B3
> A1 B3
> A2 B1
> A2 B1
> A2 B4
> A3 B2
> A3 B2
> A5 B1
> A5 B1
> A5 B6
> A5 B4
> A6 B2
>
>
>
> I want to add extra columns to the dataframe CountID1 and CountID2 which is
> the actual count of values such as A1 etc
> ie
>
>
>
> ID1 ID2 CountID1 CountID2
> A1 B3 4 3
> A1 B4 4 4
> A1 B3 4 3
> A1 B3 4 3
> A2 B1 3 4
> A2 B1 3 4
> A2 B4 3 3
> A3 B2 2 3
> A3 B2 2 3
> A5 B1 4 4
> A5 B1 4 4
> A5 B6 4 1
> A5 B4 4 4
> A6 B2 1 3
>
>
> I know this can be done by first creating temporary aggregate dataframes
> then merging with the original.
> Is there an easier way if i want to calculate many aggregates without having
> to merge many temp tables.
>
>
> Thanks.
> --
> View this message in context: http://www.nabble.com/Adding-columns-of-Aggregates-to-existing-dataframe-tp18039838p18039838.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.
>

-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

______________________________________________
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.
Received on Sat 21 Jun 2008 - 18:46:48 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 21 Jun 2008 - 20:33:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive