[R] Constructing variables conditional on two indicators

Dimitris Rizopoulos
Fri, 11 Sep 2009 07:28:52 -0000

have a look at ave() and/or tapply().

I hope it helps.

Best,
Dimitris


Reynaerts, Jo wrote:
> Dear R users
>
> I have a data frame that looks like this:
>
> m         j           X1         X2
>
> 1          1
> 1          2
> 1          ...
> 1          J
> 2          1
> 2          2
> 2          ...
> 2          J
> .
> .
> .
> M         1
> M         2
> M         ...
> M         J
>
> The data frame essentially looks like a panel: m and j are indicators where
m is 1:M and j is 1:J (and M > J); X1 and X2 are variables.  I would like to
construct and add new variables to the data frame that are m- and j- specific,
e.g., compute X3 where X3 is the sum of X1 of all j in m, and this for each m.
The new variable X3 is then added to the data frame (and is the same for all
rows with the same m indicator).
>
> How can I program this efficiently without running loops?
>
> Thanks in advance
>
> Jo Reynaerts
>
> Ph.D. student
> LICOS Centre for Institutions and Economic Performance
> Katholieke Universiteit Leuven
> Deb?riotstraat 34/3511
> B-3000 Leuven
> Belgium
> Jo.Reynaerts at econ.kuleuven.be<mailto:Jo.Reynaerts at
econ.kuleuven.be>
>
>
>
>
> 	[[alternative HTML version deleted]]
>
>
>
> ------------------------------------------------------------------------
>
> ______________________________________________
> 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.

--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014