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

maybe you want to use ave(), e.g.,

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

Address: Kapucijnenvoer 35, Leuven, Belgium

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


>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
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



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. Received on Thu 21 Jun 2007 - 14:13:36 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 Thu 21 Jun 2007 - 16:32:06 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.