Announcement

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

  • Using a forvalue loop to create variables and create variable labels

    Hi Statalist community,


    I am trying to use a forvalue loop to simultaneously create two variables and create variable labels. I am using the nlswork dataset. I am creating a variable to take the sum of the hours worked by the first three individuals in the dataset. Then I want to carry forward the values. Finally, I want to label the variables with three unique names and I used a macro to store the names. I am able to create a forvalue loop to create the variable to take the sum of the hours worked for the first three individuals and carry forward the values. However, I am not able to label the variables using the loop. Can you tell me what I am doing wrong? Thanks in advance.


    Code:
    *Use dataset
    webuse nlswork, clear
    
    *Install package if haven't
    ssc install mipolate
    
    *Count the number of observations for each individual
    quietly bysort idcode:  gen ind_obs = cond(_N==1,0,_n)
    
    *Create a  macro
    local person `" "Jack Smith" "Jane Smith"  "Joe Smith" "'
    *Failed attempt to write the loop
    *The goal is to take the hours worked, then carry forward, and then label the variables with  strings from the macro called person.
    forval i =1/3 {
        bys idcode: egen hours_work_`i' = total(hours)
        bys idcode: mipolate hours_work_`i' ind_obs, gen(sum_hours_work_`i')
        label variable sum_hours_work_`i' "Sum of hours work for `person'"
        }
    
    
    *This is what I am aiming for.
    label variable sum_hours_work_1 "Sum hours worked for Jack Smith"
    label variable sum_hours_work_2 "Sum hours worked for Jane Smith"
    label variable sum_hours_work_2 "Sum hours worked for Joe Smith"

  • #2
    Replace
    Code:
        label variable sum_hours_work_`i' "Sum of hours work for `person'"
    with
    Code:
        local pn : word `i' of `person'
        label variable sum_hours_work_`i' "Sum of hours work for `pn'"

    Comment


    • #3
      See also https://journals.sagepub.com/doi/pdf...6867X211063415

      Comment


      • #4
        @William Lisowski

        Thank you so much. It works like a charm. I am trying to be more efficient in Stata and I really appreciate your guidance.

        @Nick Cox

        Thanks for the Stata Journal article. It sounds like I am trying to run parallel loops. I didn't know how to describe what I wanted and thank you for directing me to this resource.

        Comment

        Working...
        X