SAS Macro to add a prefix to some or all variables in a data set...


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

Often we need to add a prefix to some or all variables in a dataset before we might have to merge datasets that have similar column attributes...This macro would allow you to do that....

Try it for yourself....


Copy this code and paste it in your HTML
  1. /**
  2. SAS Macro to add a prefix to some or all variables in a data set...
  3. to be used like this...
  4. %prefixvars(inpdsn,prefix,outdsn,excludevars=);
  5. inpdsn - input dataset name libname.dsnname
  6. prefix - prefix that you want to assign
  7. outdsn - output dataset name libname.dsnname
  8. excludevars - vars that you do not want to rename with the prefix
  9. **/
  10.  
  11. %macro prefixvars(inpdsn,prefix,outdsn,excludevars=);
  12.  
  13. /* split the excludevars into individual macro var names for later use*/
  14. %let num=1;
  15. %let excludevar=%scan(%upcase(&excludevars),&num,' ');
  16. %let excludevar&num=&excludevar;
  17.  
  18. %do %while(&excludevar ne );
  19. %let num=%eval(&num + 1);
  20. %let excludevar=%scan(&excludevars,&num,' ');
  21. %let excludevar&num=&excludevar;
  22. %end;
  23. %let numkeyvars=%eval(&num - 1); /* this is number of variables given in the exclude vars */
  24.  
  25.  
  26. %let dsid=%sysfunc(open(&inpdsn)); /* open the dataset and get the handle */
  27. %let numvars=%sysfunc(attrn(&dsid,nvars)); /* get the number of variables */
  28. data &outdsn;
  29. set &inpdsn(rename=(
  30. /*rename all the variables that are not in the excludevars= */
  31. %do i = 1 %to &numvars;
  32. %let flag=N;
  33. %let var&i=%sysfunc(varname(&dsid,&i));
  34. %do j=1 %to &numkeyvars;
  35. %if %upcase(&&var&i) eq &&excludevar&j %then %let flag=Y;
  36. %end;
  37. %if &flag eq N %then %do; &&var&i=&prefix&&var&i %end;
  38. %end;));
  39.  
  40. %let rc=%sysfunc(close(&dsid));
  41. run;
  42. %mend prefixvars;
  43.  
  44. /*Call the macro now*/
  45. %prefixvars(sashelp.buy,fr_,work.out,excludevars=date)

URL: http://sastechies.blogspot.com/2009/11/sas-macro-to-add-prefix-to-some-or-all.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.