DATA Step, Macro, Functions and more

Resolving string as a variable name

Reply
N/A
Posts: 0

Resolving string as a variable name

Hi All.

I have following dataset where one variable holds the value as other variable names of the same data set.

e.g.

Dataset: source_ds;
FIELD_ID FIELD_AVG FIELD_SUM REQ_STAT FIELD_STAT
01 120 240 FIELD_AVG .
02 150 300 FIELD_SUM .
03 140 260 FIELD_SUM .

Here if you see, the Field REQ_STAT contains the value of one of the other variables. Now the variable FIELD_STAT should be assigned to the value of a variable which is specified in the above REQ_STAT variable.

Hence the final output data set should look like as follow:

Dataset: TARGET_DS;
FIELD_ID FIELD_AVG FIELD_SUM REQ_STAT FIELD_STAT
01 120 240 FIELD_AVG 120
02 150 300 FIELD_SUM 300
03 140 260 FIELD_SUM 260

To achieve the same I was trying to use run time macro facility with SYMPUT and SYMGET function.

DATA target_ds;
SET source_ds;
CALL SYMPUT('field_val', req_stat);
field_stat = SYMGET('field_val');
RUN;

But when executed above code, the value of macro variable 'field_val' got resolved as a string variable rather than as a variable name.

The output was:

Dataset: TARGET_DS;
FIELD_ID FIELD_AVG FIELD_SUM REQ_STAT FIELD_STAT
01 120 240 FIELD_AVG FIELD_AVG
02 150 300 FIELD_SUM FIELD_SUM
03 140 260 FIELD_SUM FIELD_SUM

Here, in the expression, "field_stat = SYMGET('field_val');" the value returned from the symget function should be resolved as variable name rather than a string value.

Is it possible to achieve the same?
Is there any way to assign the variable name during run time?

Any help regarding this would be highly appreciated.

regards
Kapil Agrawal
Super User
Posts: 5,260

Re: Resolving string as a variable name

Macro variables will not change during data step execution, therefore does not your code work.

Your example has only two variables to chose between. The easiest is just to hard code an IF-statement. If you in you real life has tons of columns, you may want to build something more generic. If you for instance can have a name standard for you analysis column, maybe you can generate a SELECT/IF/CASE statement as a macro pre-process using table metadata.

/Linus
Data never sleeps
Ask a Question
Discussion stats
  • 1 reply
  • 128 views
  • 0 likes
  • 2 in conversation