Quantcast
Channel: SAS versus R in Analytics
Viewing all articles
Browse latest Browse all 17

SAS versus R : how to generate random numbers

$
0
0

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



Viewing all articles
Browse latest Browse all 17

Latest Images

Trending Articles





Latest Images