[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

From |
"Nick Cox" <n.j.cox@durham.ac.uk> |

To |
<statalist@hsphsun2.harvard.edu> |

Subject |
st: RE: create many variables at once |

Date |
Tue, 23 Jul 2002 10:02:21 +0100 |

Elisabeth Simantov, PhD > Perhaps someone can help me with this. I am not a > programmer, so please be explicit. > New question. > I have 19 variables that start with the prefix me_ and 19 > variables that > start with the prefix ppg_ . They all have other letters after the > underscore, actually the same for each group of 19. > > I have to create the following 19 new variables: > newvars=(me_ * var1)+(ppg_ * var1) for each observation in the data set (510) > Is there a way for me to do this in one step. If not, can > you please tell me how? Tacit in this is that there is a pairing between the -me_*- and the -ppg_*- 1. Use -for- ============ One way to do it is with -for-: for var me_* \ var ppg_* : gen stub_X_Y = var1 * (X + Y) Naturally you can devise your own naming convention. This presupposes that the two sets of variables are both in an appropriate order in memory. order me_* ppg_* would be a quick but brutal way to ensure that. In fact, although -for- has many disadvantages, it is hard to beat for conciseness here. Also, it checks that the number of variables is the same in both lists. 2. Use -forvalues- ================== Another way to do it is with -forval-: unab me : me_* unab ppg : ppg_* local nv : word count `me' forval i = 1 / `nv' { local m : word `i' of `me' local p : word `i' of `ppg' gen stub_`m'_`p' = var1 * (`m' + `p') } Same presupposition. There isn't a check here that the number of variables is the same in both lists. In your case, you know that the number of variables is 19, so you can abbreviate: unab me : me_* unab ppg : ppg_* forval i = 1 / 19 { local m : word `i' of `me' local p : word `i' of `ppg' gen stub_`m'_`p' = var1 * (`m' + `p') } 3. Use -foreach- ================ There are solutions with -foreach-. Like that with -forval-, they are typically a few lines long. Anyone see a really concise way to do it? Nick n.j.cox@durham.ac.uk * * For searches and help try: * http://www.stata.com/support/faqs/res/findit.html * http://www.stata.com/support/statalist/faq * http://www.ats.ucla.edu/stat/stata/

**References**:**st: create many variables at once***From:*owner-statalist@hsphsun2.harvard.edu

- Prev by Date:
**Re: st: create many variables at once** - Next by Date:
**st: Re: sureg** - Previous by thread:
**Re: st: create many variables at once** - Next by thread:
**st: Re: sureg** - Index(es):

© Copyright 1996–2023 StataCorp LLC | Terms of use | Privacy | Contact us | What's new | Site index |