user3741952
user3741952

Reputation: 21

Dynamically create new variable in SAS dataset using an existing variable

I have a SAS dataset:

+-------+-------+-------+-------+
| var_1 | var_2 | var_3 | index |
+-------+-------+-------+-------+
|     1 |    10 |   100 |     2 |
|     2 |    20 |   200 |     1 |
|     3 |    30 |   300 |     3 |
+-------+-------+-------+-------+

Now, I want to create a new variable in the same dataset, whose value in each row is from one of var_1, var_2 and var_3, using the corresponding entry in the index variable.

That is, if my output variable is var_out, then the dataset will look like:

+-------+-------+-------+-------+---------+
| var_1 | var_2 | var_3 | index | var_out |
+-------+-------+-------+-------+---------+
|     1 |    10 |   100 |     2 |      10 |
|     2 |    20 |   200 |     1 |       2 |
|     3 |    30 |   300 |     3 |     300 |
+-------+-------+-------+-------+---------+

Here, the first value of index is 2, hence var_out takes the value of var_2, i.e. 10

Is there any way I can do it, using macro variables if required?

Upvotes: 0

Views: 668

Answers (4)

Yegor Shakh
Yegor Shakh

Reputation: 1

If you want macro:

%macro out(i); var_&i %mend out;
data t2;
  set t1;
  call symput('index', index);
  var_out=%out(&index);
run;

Upvotes: 0

Reeza
Reeza

Reputation: 21264

The VVALUE and VVALUEX are also options though they return character values instead of numeric.

data have;
input var_1 var_2 var_3 index;
cards;
1 10 100 2
2 20 200 1
3 30 300 3
;
run;

data want;     
set have;
var_out=vvaluex("var_"|| put(index, 2. -l));
run;

http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002233818.htm

Upvotes: 0

Amir
Amir

Reputation: 1000

This can also be achieved by using functions, e.g.:

data want;
  set have;
  var_out=input(scan(catx(',', of var1-var3),index),8.);
run;

Upvotes: 0

Joe
Joe

Reputation: 63424

You would use an array.

data want;
 set have;
 array vars var1-var3;
 var_out = vars[index];
run;

Upvotes: 5

Related Questions