Search code examples
sassas-macro

How can I call a variable whose name is found as a string under another variable in SAS?


I have one variable that lists the variable name where the information I need is stored. This variable stores all the variable names as strings. I am trying to create another variable that just includes whatever is in the row of the variable whose name is stored under the first variable. For example,

var_names     var_a     var_b     new_variable    
  var_a         7         11          7
  var_a         2         9           2
  var_b         3         6           6
  var_a         6         9           6

Above var_names has the variable names and I am trying to create new_variable. Any ideas? Thanks in advance.

So far I have been working on finding a macro solution but I have been unable to get the new variable to actually equal the field rather than just the name of the variable it should be calling.

I believe the reason for this issue is that I do not know how to make a macro that is defined by another variable. i.e. %let mac = var_names and then new_variable = &varnames


Solution

  • You can use the VVALUEX function, like so:

    DATA Work.Vars;
    
        INPUT   VarToUse    $
                VarA
                VarB
                VarC
                ;
    
    DATALINES;
    VarA 1 2 3
    VarB 1 2 3
    VarC 1 2 3
    ;;;;
    RUN;
    
    DATA Work.SelectedVars;
        SET Work.Vars;
    
        Var = VVALUEX( VarToUse );
    
        KEEP    Var;
    
    RUN;
    

    Returns:

    Var
    1
    2
    3