Hi,
I am trying to create a random number and then assign it to a group according to its value.
I used very simple if-then, but it did not work!
this is my code:
data ranpatients;
seed=6789;
do i=1 to 40;
x1=int(ranuni(seed)*10000);
x=put(x1,z4.);
output;
end;
if x1 gt 5000 then group = "A"; else group = "B";
run;
When I run it, I have empty group column.
Any explanation ?
Thanks,
The order of statements is wrong.
You have implemented an algorithm that is similar to:
It is hard to put the stamp on the letter after it is already in mailbox.
data ranpatients;
seed=6789;
do i=1 to 40;
x1=int(ranuni(seed)*10000);
x=put(x1,z4.);
if x1 gt 5000 then group = "A"; else group = "B";
output;
end;
run;
The IF statement has to go before the OUTPUT statement.
Otherwise (the way you have it), the record is output to the data set RANPATIENTS before GROUP is assigned a value, so GROUP is always missing.
@lansoprazole wrote:
Thanks.
I tried it but the first observation (raw) was not assigned any group.
I will try it again.
I tried it too, and group is assigned to every observation in the data set. If it is not working for you, SHOW US the code.
The order of statements is wrong.
You have implemented an algorithm that is similar to:
It is hard to put the stamp on the letter after it is already in mailbox.
data ranpatients;
seed=6789;
do i=1 to 40;
x1=int(ranuni(seed)*10000);
x=put(x1,z4.);
if x1 gt 5000 then group = "A"; else group = "B";
output;
end;
run;
If a data step dos not have an explicit OUTPUT statements then SAS will automatically OUTPUT (write the current values to the saved dataset) at the end of the step.
But your code has an OUTPUT statement so there is no extra output added.
If you want the value of GROUP to depend on the value of X you have to calculate GROUP before you write the data to the file.
@lansoprazole wrote:
Thanks.
so output should be always at the end? or because I am using a variable from the loop?
I don't know if it should ALWAYS be at the end, as there may be examples where OUTPUT is not at the end.
What you are being advised to do is assign the value of GROUP before the OUTPUT.
Apart from moving the IF, you should also consider using the more modern (and recommended) RAND function:
data ranpatients;
call streaminit(6789);
do i = 1 to 40;
x1 = rand("integer",1,9999);
if x1 gt 5000 then group = "A"; else group = "B";
x = put(x1,z4.);
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.