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

StackOverflow https://stackoverflow.com/questions/17534219

  •  02-06-2022
  •  | 
  •  

Question

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

Was it helpful?

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

OTHER TIPS

Cyborgx37's answer (VValueX) is definitely the way to go. The reason you weren't able to do this with macro variables is that the macro variable stores the text of the variable name (so in your example, var_names) not the value of that variable. You couldn't use it during the data step, because a macro variable isn't available during the data step it's created in to be used for compile-time purposes (such as getting the value of a variable named that).

You could go as far as this:

data have;
input var_names $ var_a     var_b     new_variable ;
datalines;
var_a         7         11          7
var_a         2         9           2
var_b         3         6           6
var_a         6         9           6
;;;;
run;

data want;
set have;
call symput("varname",var_names);
x = symget("varname");
put x=;
run;

But there, x stores "var_a"; you aren't allowed to use "var_a" as a variable name in that context. There isn't really a good macro solution here; you could store all of the values of var_names in a delimited string and parse that, but it would be pretty messy and involves putting data into a macro variable, which violates proper program design principles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top