Announcement

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

  • Using global for varlist

    Hey!

    I am declaring a global macro with a list of variables to do a loop, and then keep only those variables. While the global option is working on the loop, it is not working with the keep command. Any ideas why?

    Code:
     global variables risk_general risk_driving risk_finances 
    foreach var of global variables {
    gen `var' = `var'_2010 if `var'_2010 >= 0 
    replace `var' = `var'_2011 if `var'_2011 >= 0
    }
    
    keep `variables'
    The error I am getting is:

    varlist, if exp, or in range required

    Which I assume Stata is not understanding that my global `variables' is a varilist. What am I doing wrong?

    Thanks!!

  • #2
    I can't see a problem here with your code, but watch out: missing values count as greater than zero.

    Comment


    • #3
      Thanks Nick. This is wierd. I know, in my case missing values are coded as negative numbers. Thanks for the help!

      Comment


      • #4
        So, that is not an issue. Here's a different question: Are you running the code all at once, or line by line from a do-file editor window? If the second. then the definition of var will not be visible when you refer to it. The code could be

        f
        Code:
        oreach var in general risk finances { 
             gen risk_`var' = risk_`var'_2010 if risk_`var'_2010 >= 0 
             replace risk_`var' = risk_`var'_2011 if risk_`var'_2011 >= 0 
        }
        but must be run as a whole, not line by line.

        I find it hard to imagine that you should
        keep only these variables.

        Comment


        • #5
          Regarding the original code fragment: Because -variables- is a global and not a local, shouldn't the last line be
          Code:
          keep $variables

          Comment


          • #6
            @Mlke Lacy is quite right. This would be an explanation of the error message. But do you really want to get rid of everything else?

            Comment


            • #7
              Thanks for the answers!

              Comment

              Working...
              X