SAS versus R : how to generate random numbers

In SAS, “ranuni” function can be used to generate random numbers between 0 and 1 inclusive. Hence, if there is a request to generate random numbers from 1 to 5 inclusive, it is possible to multiply by 5 and add 1 to the result which is then rounded to the integer portion of the decimal point.

Example in SAS 

data random_number;
do i=1 to 5;
rand_num = int(ranuni(0) * 5 + 1);
output;
end;

In R on the other hand, we can just use a “sample” function to derive random numbers from 1 to 5. Colon (:) specifies the range directly, which in my opinion, makes the code very convenient to read and maintain.

Example in R

> x3 <- sample(1:5, 5)
> print( x3 )
[1] 2 5 3 1 4

Notice that there were no repetitions in R in the example above. Having a third parameter in the example below allows repetitions.

> x3 <- sample(1:5, 5, replace=T)
> print ( x3 )
[1] 3 1 3 1 3

SAS versus R : how to generate random numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s