Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Looping over variables

    Hi there,

    I'm trying to generate prevalence variable based on the calculation of two variables in the dataset.

    How would I condense the following into a loop (I want to create separate variables for the years 2007 to 2018):

    gen lsoapsyprev_2007 = (lsoapsych_2007/ LSOAmye_pop2007)*100
    gen lsoapsyprev_2008 = (lsoapsych_2008/ LSOAmye_pop2008)*100
    gen lsoapsyprev_2009 = (lsoapsych_2009/ LSOAmye_pop2009)*100

    Many thanks

  • #2
    This should work
    Code:
    foreach n in 2007 2008 2009 {
    gen lsoapsyprev_`n' = (lsoapsych_`n'/ LSOAmye_pop`n')*100
    }
    EDIT.
    Just read that you want to do it till 2018. Then you could do

    Code:
    foreach n of numlist 2007/2018 {
    gen lsoapsyprev_`n' = (lsoapsych_`n'/ LSOAmye_pop`n')*100
    }
    Last edited by Demetrio Guzzardi; 07 Feb 2024, 06:48.

    Comment


    • #3
      Thank you so much!

      Comment


      • #4
        I'll add the usual comment here that you have what in Stata circles is called a wide layout (structure, format). For almost all purposes you would be better off working long.

        Another way to put this: You start out with 24 variables, and you're adding 12 more. Come a similar problem, 12 more. And so on. Also, given data for various years you should be wanting, at some point, graphs against year or some kind of time series analysis.. How are you going to do with your present layout?
        Last edited by Nick Cox; 07 Feb 2024, 07:55.

        Comment

        Working...
        X