Hi,
suppose that I have a table with 10 ids. Is it possible to create a new variable called "group" such that there are only say 3 groups and they are repetitive in the form 3,1,2,3,1,2,3,1,2 etc:
id | group |
1 | 3 |
2 | 1 |
3 | 2 |
4 | 3 |
5 | 1 |
6 | 2 |
7 | 3 |
8 | 1 |
9 | 2 |
10 | 3 |
Thank you!
Use function mode() to create the group code:
data test;
retain group 3; /* initial value, may be adapted to start with that value */
do id=1 to 10;
output;
group = mod(group,3) +1;
end;
run;
Use function mode() to create the group code:
data test;
retain group 3; /* initial value, may be adapted to start with that value */
do id=1 to 10;
output;
group = mod(group,3) +1;
end;
run;
Umm - I think you mean 'mod'…
Thanks for the code it works perfectly!
But suppsoe that instead of the groups 3,1,2 I had groups a,b,c - is it possible to have a more universal solution which can accomodate for any groups?
Using the 'more than one way to skin a cat' process:
data test;
array group_array{3} $ 1 _temporary_ ('a', 'b', 'c');
retain groupn 2; /* initial value, may be adapted to start with that value */
do id=1 to 10;
groupn = mod(groupn, 3) + 1;
group = group_array[groupn];
output;
end;
keep id group;
run;
Assigning the values to an array, then using the mod-ed groupn value, you get (in order) c / a / b / c…
data have; array x{3} $ _temporary_ ('c' 'a' 'b'); do id=1 to 10; if mod(id,3)=1 then n=0; n+1; group=x{n}; output; end; run;
data have; array x{3} $ _temporary_ ('c' 'a' 'b'); do id=1 to 10; if mod(id,3)=1 then n=0; n+1; group=x{n}; output; end; run;
is it possible to assign a list such that:
array x{3} $ _temporary_ &list;
Yes definitely. You have to be careful as to how you construct "&list", with the quoting especially, but it would be a great generalised solution.
Thanks!
Strictly speaking, Shmuel's post is the answer to the question as I formulated it, but the other posts give immense insight into the general solution!
data have; array x{3} $ _temporary_ ('c' 'a' 'b'); do id=1 to 10; if mod(id,3)=1 then n=0; n+1; group=x{n}; output; end; run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.