Announcement

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

  • replacing values of a newly generated variable by the values of previous variables using "foreach var of varlist"

    Hi everyone,
    Using the below codes, I am trying to generate a new variable (long_X6 to long_X13) and replace its values by the values of the preceding variable or X5 to X12 (coded as `var'-1==2). I do not get any errors when run this code but nothing happens in the data.
    Thanks,
    Nader

    foreach var of varlist X6-X13 {
    replace long_`var'=2 if `var'-1==2
    }

  • #2
    `var'-1==2 doesn't subtract 1 from the variable name, it subtracts 1 from the value of each observation of `var' and checks whether it's equal to two.
    You could do something like this.
    Code:
    forval i = 6/13 {
        gen long_X`i' = 2 if X`=`i'-1' == 2
        }

    Comment


    • #3
      Thanks Wouter; this works perfectly. Is there any way to label the value of the new variable (i.e.,
      long_X`i') within the loop; Somthing like "spousal long-term caregiver"?

      Comment


      • #4
        Yes, then I would do it a bit differently:
        Code:
        local counter = 6
        foreach label in label_one label_two label_three etc.{ // define labels for all variables
            gen long_X`counter' = 2 if X`=`counter'-1' == 2
            lab var long_X`counter' `label'
            local counter = `counter' + 1
        }

        Comment


        • #5
          Wouter Wakker gives excellent advice. Consistent with that is to wonder whether you have the best data layout. If variables are regarded as "previous" or "following", a long layout may be a better idea.

          Comment

          Working...
          X