[R] Adding columns of Aggregates to existing dataframe
jim holtman
jholtman at gmail.com
Sat Jun 21 20:43:54 CEST 2008
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?
More information about the R-help
mailing list