Announcement

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

  • Local list of variables as argument of program

    I'm trying to enter a list of variables as an argument for a program. Unfortunately, I've been running into some problem.

    I made the program to have a unique argument, "outcomes", and then I insert the first argument for the code as a local containing two variables, "x" and "y".

    The code only produces x_post_std instead of also producing y_post_std.

    I checked the program arguments section of the help file, but it had no information about inputting a local as an argument.

    Code:
    cap program drop test
    program test
    
    * Arguments: components and covariates
    args outcomes
    {
    
    * Step 1: Standardize variables
        foreach var in `outcomes' {
        di "`var'"
                
            * Create standardized versions
            cap drop `var'_post_std
            
            sum `var'
            gen `var'_post_mean = r(mean)
            gen `var'_post_sd = r(sd)
            gen `var'_post_std = (`var' - `var'_post_mean) / `var'_post_sd
            drop `var'_post_mean `var'_post_sd
            
    }    
    }
    end
    
    clear
    set obs 20
    gen x = rnormal()
    gen y = rnormal()
    
    local variables "x y"
    
    test `variables'

  • #2
    Note, -test- is already a command. I would change the name to something like -mytest-.

    -args- thinks you are giving it two positional arguments but you only have one macroname. If you bind the local macro `variables' in another set of quotes it will work:

    Code:
    local variables "x y"
    mytest "`variables'"
    l

    Comment


    • #3
      Scott Merryman makes two utterly fundamental points in his very helpful post. Here are some more.

      Writing your own command to do this is hard to understand unless it is the start of something more comprehensive,

      The same functionality (with flexibility to change) comes from

      Code:
      foreach v in x y {
            capture drop `v'_post_std
            egen `v'_post_std  = std(`v')
      } 
      If your program is the start of something bigger, you don't need to create new variables you know you are going to drop

      This pushes your design a step further.

      Code:
      program whatever
      version 7
      syntax varlist(numeric)
      
      foreach var of local varlist {
          di "`var'"
          cap drop `var'_post_std
          sum `var'
          gen `var'_post_std = (`var' - r(mean)) /  r(sd)
      }
      
      end




      Last edited by Nick Cox; 25 Oct 2019, 03:23.

      Comment

      Working...
      X