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;
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 lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.
Ready to level-up your skills? Choose your own adventure.