Setting variable value based on value of another variable.


/ Published in: SAS
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*The Data we have is this:*/
  2.  
  3. DATA Temp;
  4. Input Var200203 Var200204 Var200205 VarLookUp $11.;
  5. DataLines;
  6. 1 2 3 Var200203
  7. 5 6 7 Var200204
  8. 3 6 9 Var200205
  9. ;
  10. RUN;
  11.  
  12. /*We want to end up with VarOut which is the value of the lookup column for that observation:
  13.  
  14. Var200203 Var200204 Var200205 VarLookUp VarOut
  15. 1 2 3 Var200203 1
  16. 5 6 7 Var200204 6
  17. 3 6 9 Var200205 9
  18. */
  19.  
  20. /*The solution:
  21.  
  22. While the vname function is comparatively expensive, it’s helpful here.
  23. One additional data line added to test with unexpected data.*/
  24.  
  25. DATA Temp;
  26. Input Var200203 Var200204 Var200205 VarLookUp $11.;
  27. DataLines;
  28. 1 2 3 Var200203
  29. 5 6 7 Var200204
  30. 3 6 9 Var200205
  31. 3 6 9 Var200206
  32. ;
  33. 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;
  34.  
  35. proc print data=done;
  36. run;
  37.  
  38. /*
  39. The SAS System 09:21 Thursday, July 31, 2003 1
  40.  
  41. Obs Var200203 Var200204 Var200205 VarLookUp varout
  42.  
  43. 1 1 2 3 Var200203 1
  44. 2 5 6 7 Var200204 6
  45. 3 3 6 9 Var200205 9
  46. 4 3 6 9 Var200206 .
  47. */

URL: http://jaredprins.squarespace.com/blog/2008/3/31/setting-variable-value-based-on-value-of-another-variable.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.