I have variables cnt1 through cnt11. They are numeric (containing values between 1 and 15), but I need to make these variables character. If there is someway to do this without a loop, that would be great; but it seems this may only work with a loop. The following is what I want to work, but I realize this is not how you specify how you iterate through variable names with different numeric suffixes. Does anyone know how to do this?
data want; set have do i=1 to &max_n_off; ocnt&i. = put(cnt&i., 3.); end; run;
I would go wiht @SASKiwi 's solution, but just to complete the macro approach you were considering:
%macro doloop(upper_limit=);
data want;
set have;
%do i=1 %to &upper_limit;
c&i=put(x&i,4.);
%end;
run;
%mend doloop;
options mprint;
%doloop(upper_limit=3);
Way too much typing.
Easy to do with arrays:
data want;
set have
array cnts (*) cnt1 - cnt11;
array ocnts (*) $ 3 ocnt1 - ocnt11;
do i=1 to dim(cnts);
ocnts (i). = left(put(cnts(i), 3.));
end;
run;
I would go wiht @SASKiwi 's solution, but just to complete the macro approach you were considering:
%macro doloop(upper_limit=);
data want;
set have;
%do i=1 %to &upper_limit;
c&i=put(x&i,4.);
%end;
run;
%mend doloop;
options mprint;
%doloop(upper_limit=3);
Way too much typing.
Agreeing with @SASKiwi and @mkeintz that ARRAYs are the way to do this, but to explain further, you cannot mix and match macro language and data step language the way you have done in your original code. In your original code, you refer to macro variable &i but you never define macro variable &i or give it a value. In addition, macro variables are not data set variables, and vice versa. Just because you have a data set variable named i does not mean it has any relationship to a macro variable &i.
You use ARRAY statement to allow you to loop over a list of variables.
You will need to make new variables since you cannot change the existing variables.
If you want to re-use the names you can use RENAME to change the names back.
data want;
set have ;
array old cnt1-cnt15 ;
array new $3 ocnt1-ocnt15;
do index=1 to dim(old);
new[index] = put(old[index],3.);
end;
drop index;
rename cnt1-cnt15=charcnt1-charcnt15 ocnt1-ocnt15=cnt1-cnt15 ;
run;
Do you really want your new character values to have leading spaces if the number is less than 100?
If not you can use either the Z3. format to include leading zeros instead.
Or use the -L format modifier to left align the values.
new[index] = put(old[index],3.-L);
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.