Hello everyone, I'm newish to SAS, so please bare with me. I'm trying to create multiple flag variables based on the contents of a parsed out variable. My macro isn't doing what I want it to do... it's parameter is passing as a static string, rather than a dynamic variable. Any help would be greatly appreciated.
-----------
Details!
This is my input data:
data Input;
input Variable_source $15.;
datalines;
01 03
01 03 04
01 05
01 02
;Here is my Macro code
%macro parse (temp=);
data output; set Input;
%local i;
%do i = 1 %to %sysfunc(countw(&temp));
%let code = %scan(&temp, &i, %str( ));
VARIABLE_&code=1;
%end;
run;
%mend;
%parse (temp=Variable_source);
It gives me this:
| Variable_source | VARIABLE_variable_source |
| 01 03 | 1 |
| 01 03 04 | 1 |
| 01 05 | 1 |
| 01 02 | 1 |
But I want this:
| Variable_source | VARIABLE_01 | VARIABLE_02 | VARIABLE_03 | VARIABLE_04 | VARIABLE_05 |
| 01 03 | 1 | 1 | |||
| 01 03 04 | 1 | 1 | 1 | ||
| 01 05 | 1 | 1 | |||
| 01 02 | 1 | 1 |
Hello!
The reason your macro doesn't work is because the macro is compiled before the data step is processed, i.e. the countw(&temp) will translate into countw(Variable_source) = 1 (same with the %scan()-function).
This is one way of doing it without using a macro:
data Input;
input Variable_source $15.;
datalines;
01 03
01 03 04
01 05
01 02
;
/* Looping through each dynamic array (using scan() to loop through the "words" and outputing each source as a new row) */
/* Creating dummy variable transpose_var=1 for transpose below and temporary variable rownumber to avoid sorting issues when transposing */
data work.input_spliced(drop=i);
set work.input;
rownumber = _n_;
transpose_var = 1;
do i = 1 to countw(Variable_source);
Var_source_spliced = scan(Variable_source,i);
output;
end;
run;
/* Transposing the spliced table with variable prefix VARIABLE_ */
proc transpose data=work.input_spliced out=work.output(drop=rownumber _name_) prefix=VARIABLE_;
by rownumber Variable_source;
id Var_source_spliced;
var transpose_var;
run;
Kind regards
/Calle
Edit: Realized there was some unnecessary code in there, so I trimmed the solution a bit. 🙂
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and save with the early bird rate—just $795!
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.