# Re: [R] generating a new variable based on results of a by command

From: Dimitris Rizopoulos <dimitris.rizopoulos_at_med.kuleuven.be>
Date: Thu, 21 Jun 2007 16:00:36 +0200

f\$sums <- ave(f\$b, f\$e, FUN = sum)

I hope it helps.

Best,
Dimitris

Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

```Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
http://www.student.kuleuven.be/~m0390867/dimitris.htm

```
• Original Message ----- From: "Economics Guy" <economics.guy_at_gmail.com> To: <r-help_at_stat.math.ethz.ch> Sent: Thursday, June 21, 2007 3:53 PM Subject: [R] generating a new variable based on results of a by command

>I have a matrix with a set of variables one of which is a factor.
>Using by()
> I have calculated something about each group (say the sum). Now I
> want to
> create a new variable in the original matrix that contains the
> results of
> the by() for each observation that is in the corresponding group.
>
> For example I have:
>
> ---------
>
> a <-c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
>
> b <-c(7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22)
>
> e
> <-c("A","B","C","D","E","F","A","B","C","D","E","F","D","E","F","A")
>
> f <-data.frame(e,a,b)
>
> # Calculate sum by group
>
> sums <- by(f, e, function(x) sum(x\$b))
>
> -----------
>
> Now I would like to assign each observation in f a new variable
> based on the
> results of the by(). I converted sums into a matrix and then tried
> using
> match() and ifthen() but could not get it to work.
>
> Thanks,
>
> EG
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help