Hi,
I have an array of length n, for example :
ARRAY _Example{*} 6$ EXA001:
I want to randomly select an element of the array. Is there an easy or straight forward way of achieving this?
The larger scope of this issue is that I want to assign a random element of the the array (map the element for example EXA004) to a dataset. Essentially, randomly assign one of the elements of the array to an ID variable.
Any insight into this issue would be much appreciated.
Cheers.
Assuming that the syntax for the array statement gets fixed ...
data want;
set have;
array _Example {*} whatever goes here;
r = ceil( dim(_Example) * ranuni(12345) ) ;
randomly_selected_element = _Example{r};
run;
The variable R will be a randomly selected integer, minimum is 1 and maximum is number of elements in the array.
The test that I tried with this logic will not populate the random_element column with the array element.
data test; array _Example{*} $6. TEST01-TEST10 ; r = ceil(dim(_Vendor) * ranuni(12345)); random_element = _Example{r}; run;
I appreciate your help, please bear with me as I am a new SAS user.
You don't have a SET statement. Don't you have an input dataset?
You lost me now.
I still suspect you need to add the SET statement.
OR if you're creating a new data set from scratch you need a loop with an output statement.
do i=1 to 1000; *number of records;
x= .... ;
output;
end;
1. Generate a random uniform variable between 1 and 6. This assumes you're using SAS 9.4 TS1M4+, if you don't, use the approach outlined here
rand_int = rand('Integer', 1, 6);
2. Use that index in the array to map the value over.
value = _example(rand_int);
@lhsumdalum wrote:
Hi,
I have an array of length n, for example :
ARRAY _Example{*} 6$ EXA001:
I want to randomly select an element of the array. Is there an easy or straight forward way of achieving this?
The larger scope of this issue is that I want to assign a random element of the the array (map the element for example EXA004) to a dataset. Essentially, randomly assign one of the elements of the array to an ID variable.
Any insight into this issue would be much appreciated.
Cheers.
Is it possible to replace the hard-coded upper bound of 6 with the unspecified dimension of the array? To continue your example, as such:
rand_int = rand('Integer', 1, dim(_Example));
I don't know, did it work?
@lhsumdalum wrote:
Is it possible to replace the hard-coded upper bound of 6 with the unspecified dimension of the array? To continue your example, as such:
rand_int = rand('Integer', 1, dim(_Example));
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 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.