Announcement

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

  • multiple foreach for replacing value not working

    Hi,

    I want to use 2 foreach. Basically, I want to get age of a specific person(self_age) in (varlist1) from the varlist2 of the specific person ( where var1==1).

    But, I am not getting all the age in the rows with this command

    Code:
    gen self_age=.
    foreach var1 of varlist age_1 age_2 age_3 age_4 {
    foreach var2 of varlist name_code_a name_code_b name_code_c name_code_d name_code_e name_code_f name_code_g name_code_h name_code_i {
    replace self_age= `var1' if `var2'==1
    }
    }

    The problem is it is replacing the age of ONLY "age_4" and "name_code_i" and rest all the observations are replacing as missing ".". How can I can I get self_age in one var?

  • #2
    The problem is basically, in the qs the age of the responded was not mentioned. But, the age was mentioned in the family relationship section as self age. self was coded as 1 in multiple variables. while corresponding age of the self are scattered in other family age variables.

    Comment


    • #3
      in your loop when var1 is age_1 self age is replaced then self age gets replaced again (overwritten) when age_2 is active in the loop and so on. So, that is why you see correct results for age_4 because that is the last value of var1 and nothing replaces it. Without seeing the data it is difficult to come up with an exact answer. If you want to stick to he same code and make it work you might want to try something like

      gen self_age_1=.
      gen self_age_2=.
      gen self_age_3=.
      gen self_age_4=.
      forvalues n = 1/4 {
      foreach var2 of varlist name_code_a name_code_b name_code_c name_code_d name_code_e name_code_f name_code_g name_code_h name_code_i {
      replace self_age`n'= age_`n' if `var2'==1
      }
      }
      gen self_age_combined =.
      replace self_age_combined = self_age_1 if self_age_1 !=.
      replace self_age_combined = self_age_2 if self_age_2 !=.
      replace self_age_combined = self_age_3 if self_age_3 !=.
      replace self_age_combined = self_age_4 if self_age_4 !=.

      This assumes that self_age_`n' would not be missing only if when it is correct.
      Last edited by Oscar Ozfidan; 14 May 2021, 15:02.

      Comment


      • #4
        This question is nothing to do with Mata, so please post similar questions in General in future.

        Oscar Ozfidan 's helpful code can be slimmed, I think, to

        Code:
        gen self_age_combined =.
        
        local args name_code_a 
        foreach v in b c d e f g h i { 
            local args `args', name_code_`v' 
        }
        
        forvalues n = 1/4 {
           gen self_age_`n' = age_`n' if inlist(1, `args')  
           replace self_age_combined = self_age_`n' if self_age_`n' != .
        }

        Comment

        Working...
        X