Setting variable value based on value of another variable
I thought that this was a rather interesting solution to Setting variable value based on value of another variable.
The Data we have is this:
DATA Temp;
Input Var200203 Var200204 Var200205 VarLookUp $11.;
DataLines;
1 2 3 Var200203
5 6 7 Var200204
3 6 9 Var200205
;
RUN;
We want to end up with VarOut which is the value of the lookup column for that observation:
Var200203 Var200204 Var200205 VarLookUp VarOut
1 2 3 Var200203 1
5 6 7 Var200204 6
3 6 9 Var200205 9
The solution:
While the vname function is comparatively expensive, it’s helpful here.
One additional data line added to test with unexpected data.
DATA Temp;
Input Var200203 Var200204 Var200205 VarLookUp $11.;
DataLines;
1 2 3 Var200203
5 6 7 Var200204
3 6 9 Var200205
3 6 9 Var200206
;
data done ( drop = _: ); set temp; array vars var2: ; do _i = 1 to dim(vars) until (vname(vars(_i)) = varlookup) ; end; if _i le dim(vars) then varout = vars(_i); run;
proc print data=done;
run;
Result:
The SAS System 09:21 Thursday, July 31, 2003 1
Obs Var200203 Var200204 Var200205 VarLookUp varout
1 1 2 3 Var200203 1
2 5 6 7 Var200204 6
3 3 6 9 Var200205 9
4 3 6 9 Var200206 .
I have a feeling this code will be helpful for me in the upcoming year.


Reader Comments