Reputation: 11
I have a fixed field in a SAS dataset. Let's call it cost. I want to create 20 different columns. Cost - 5, Cost - 10, Cost - 15, and so on, but I don't want to code this out because I need to do this for several fields.
Can someone show me how I could do this in a do loop in SAS? Or if there is an easier way to do this, I would love to know. Thanks!
Upvotes: 1
Views: 2135
Reputation: 63424
The general approach here is to use arrays, and possibly macros with those arrays if you are doing this for multiple things.
data class;
set sashelp.class;
array ages[5]; *your array, holding your 5 new columns;
do _i = 1 to 5; *loop over the array;
ages[_i] = age-_i; *or -(5*_i) or whatever you are doing;
end;
run;
Then, if you want to do that for many variables, take those four lines, put them in a macro, create parameters for whatever might change, and call it from a datastep however many times you need. The loop is inside the macro and is a data step loop, not a macro loop.
You can explicitly name the variables in the array statement, or just take what SAS does by default. You could also create a macro to create the named variables if you want them to be named intelligently.
Upvotes: 2