DATA Step, Macro, Functions and more

set variable equal to a randomly chosen value from a list

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

set variable equal to a randomly chosen value from a list

Hello,

 

I am attempting the following for each observation in my dataset.

 

x=SelectRandomlyFrom("A","B","C")

 

That's it.  I can use ranuni or proc surveyselect to select one of the options but i can't figure out how to set x equal to the output.

 

it doesn't matter to me if my choices have to be in a dataset or simply a typed list.

 

Any help would be appreciated.

 

thank you.


Accepted Solutions
Solution
‎06-07-2017 10:28 AM
PROC Star
Posts: 102

Re: set variable equal to a randomly chosen value from a list

Posted in reply to the_sheriff

@the_sheriff: The CHOOSEC is probably the easiest way in your example:

x=ChooseC(ceil(Rand('UNIFORM')*3),"A","B","C");

If your data is in an array, this is the format:

array values c1-c60;
x=ChooseC(ceil(Rand('UNIFORM')*dim(values)),of values(*));

I recommend using RAND() instead of RANUNI(), as it is a better pseudorandom algorithm.

 

View solution in original post


All Replies
Frequent Contributor
Posts: 110

Re: set variable equal to a randomly chosen value from a list

Posted in reply to the_sheriff

If you only want to select random As, Bs, and Cs, the following code will take care of it:

data work.want;
	do i=1 to 10;
	random_ABC = substr('ABC',ceil(ranuni(0)*3),1);
	output;
   	end;
run;
Super User
Posts: 19,867

Re: set variable equal to a randomly chosen value from a list

Posted in reply to the_sheriff
Solution
‎06-07-2017 10:28 AM
PROC Star
Posts: 102

Re: set variable equal to a randomly chosen value from a list

Posted in reply to the_sheriff

@the_sheriff: The CHOOSEC is probably the easiest way in your example:

x=ChooseC(ceil(Rand('UNIFORM')*3),"A","B","C");

If your data is in an array, this is the format:

array values c1-c60;
x=ChooseC(ceil(Rand('UNIFORM')*dim(values)),of values(*));

I recommend using RAND() instead of RANUNI(), as it is a better pseudorandom algorithm.

 

New Contributor
Posts: 2

Re: set variable equal to a randomly chosen value from a list

Always great to learn something new. This is exactly what i was looking for. Thank you.
SAS Super FREQ
Posts: 3,755

Re: set variable equal to a randomly chosen value from a list

Posted in reply to the_sheriff

You can generalize @s_lassen's solution to the case of unequal probabilities, as described in the blog post

"Simulate categorical data in SAS"

 

data Sample; 
keep i j x; 
array prob [3] (0.5 0.2 0.3);       /* unequal probabilities */
array values [3] $ ("A" "B" "C"); /* categories */
call streaminit(54321); 
do i = 1 to 100;
   j = rand("Table", of prob[*]);
   x = values[j];
   output; 
end; 
run;
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 155 views
  • 8 likes
  • 5 in conversation