Announcement

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

  • Forvalues loop: Replacing value of local macro if local macro takes specific value

    Dear all,

    I have a variable of the form income_yyyy_mm where 'yyyy' refers to the year and 'mm' refers to the month. The variable shows the income status of an individual, and the value '.' means no income.

    I have another variable again of the form xyyyy_mm where 'yyyy' again refers to the year and 'mm' refers to the month. I need this variable to take the value 1, if the individual had no income in the previous month.

    Writing

    Code:
    forval i = 1/12 {
    forval j = 2014/2021 {
    local k = `i' - 1
    
    replace x´j'_´i' = 1 if ///
    income_´j'_´i' ==.
    }
    }
    returns
    Code:
    income_2014_0 not found
    which is because there is no "month zero" of my data in 2014. I need the first line to refer to month 12 in the preceding year. My own suggestion of solving the first part of this problem, i.e., making ´k' show 12 if `i' is 1 does not work. Writing:

    Code:
    forval i = 1/12 {
    forval j = 2014/2021 {
    local k = `i' - 1
    replace `k'=12 if `k'==0
    
    replace x´j'_´i' = 1 if ///
    income_´j'_´i' ==.
    }
    }
    Returns
    Code:
    0 invalid name
    I do know that there are two parts of my problem (because of the years also need to change) but I believe I could solve the year-part of the problem, if I understood how to solve the month part of the problem. So how do I replace the value of local macro if the local macro takes on a specific value?

  • #2
    On the evidence here this awkward problem arises because you are holding data in wide layout when long layout is strongly preferable. Not just this problem but anything similar will be painful to formulate and solve. Also, at every step you are creating a bundle of new variables when there is need only for one, referring to the previous month.

    I strongly advise reshape long to make your immediate Stata future much more comfortable.

    Comment

    Working...
    X