# 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 )
 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 )
 3 1 3 1 3

# SAS versus R : using arrays

In a general programming language, an array is considered to be a data structure which stores variables of similar data type. In SAS, this is not the case. An array is only a compile-time statement and thus, it will not exist outside the scope of the calling data step.

In R, arrays are created from a data structure called vectors using a c() function. This function combines values of similar data types. Once a vector is created, the vector name is passed as a value to an “array” function.

Example in SAS

data temp;

array color_array{3} \$8 ( ‘Purple’, ‘Brown’, ‘Red’ );
putlog “Second element in the array is ” color_array{2};

run;

Example in R

> colors <- c( ‘Purple’, ‘Brown’, ‘Red’)
> print ( colors )
 “Purple” “Brown” “Red”
> color_array <- array ( colors )
> print ( class ( color_array ))
 “array”
> print( color_array )
 “Brown”

# SAS versus R : using lists

I have an extensive background in Base SAS and SAS suite of tools. But R is fairly new to me and I’ve been studying it in my spare time. I figure the best way to learn R is to compare it with SAS. I have SAS University Edition and RStudio on my personal laptop.

For this first blog, I will start with lists in SAS. Lists allow a series of number to be mentioned in a simplified manner in a function. For example, if I want to find an average of 1, 2, 3, 4 and 5, I don’t have to mention all these numbers in the “mean” function. I can use “of” in the function to specify the list.

Example in SAS

data temp;

array t{5} (1 2 3 4 5);

avg_num=mean( of t1-t5);

run;

R is even easier. It took me just one line to compute the mean.

Example in R

print ( mean(1:5))
 3