Solved
Contributor
Posts: 68

# Randomly select a number

Hi guys,

If I want to create a data set and randomly select a number from 11, 30, 16, 19, 22 for each observation from 1 to 1000.

What should I do?

N     X

1     11

2     11

3     19

.....

Accepted Solutions
Solution
‎09-10-2014 08:47 PM
Posts: 5,543

## Re: Randomly select a number

Another way:

data want;

call streaminit(7879);

do n = 1 to 1000;

x = choosen(rand("TABLE",.2,.2,.2,.2), 11, 30, 16, 19, 22);

output;

end;

run;

proc print data=want(obs=20) noobs; run;

PG

PG

All Replies
Super User
Posts: 13,583

## Re: Randomly select a number

data want;

array t{5} _temporary_ (11 30 16 19 22);

do n= 1 to 1000;

x= t[round (( 5* ranuni(0) + 0.5),1)];

output;

end;

run;

Valued Guide
Posts: 595

## Re: Randomly select a number

There are a number of different ways of doing this - here's one way of doing it so that the selection is made with a uniform distribution. If you want a different distribution there are a large number to choose from - just check the documentation for the rand function.

data want(keep=n x);

/* Create an array to hold the numbers to choose from */

array valid_nums [5] (11 30 16 19 22);

/* Loop through creating random integers from 1 to 5 and pick out the selected number as the array index */

do i =1 to 1000;

n=_n_;

x=valid_nums{ceil(rand("uniform")*5)};

output;

end;

run;

/* You can check the output follows a uniform distribution using proc freq */

proc freq data=want;

run;

Chris

Solution
‎09-10-2014 08:47 PM
Posts: 5,543

## Re: Randomly select a number

Another way:

data want;

call streaminit(7879);

do n = 1 to 1000;

x = choosen(rand("TABLE",.2,.2,.2,.2), 11, 30, 16, 19, 22);

output;

end;

run;

proc print data=want(obs=20) noobs; run;

PG

PG
Contributor
Posts: 68

## Re: Randomly select a number

Hi PG,

I'm thinking of the principle behind the x=rand('TABLE',.2,.2...) statement.

take x=rand('TABLE',.2,.5); for example, why it resolved to a number of 2? What does argument .2 here mean?

I would greatly appreciate if you can get back to me. Thank you in advance.

Posts: 5,543

## Re: Randomly select a number

Check the doc for function RAND with the "TABLE" argument

SAS(R) 9.3 Functions and CALL Routines: Reference

x=rand('TABLE',.2,.5);will return randomly 1, 2 or 3 with probabilities 0.2, 0.5, and 0.3 respectively. The last probability, 0.3 = 1 - (0.2 + 0.5), doesn't have to be specified. In other terms, rand("TABLE",...) returns a random multinomial number.

PG

PG
🔒 This topic is solved and locked.