6 C
London
Tuesday, March 11, 2025
HomeSASData Munging in SASHow to Generate Random Numbers in SAS (3 Examples)

How to Generate Random Numbers in SAS (3 Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the rand() function in SAS to generate random numbers.

The following examples show how to use this function in practice.

Example 1: Generate One Random Number

The following code shows how to generate a single random integer in SAS between 1 and 10:

/*create dataset with variable that contain random value*/
data my_data;
   call streaminit(1);  /*make this example reproducible*/
   x = rand("integer", 1, 10);
   output;
run;

/*view dataset*/
proc print data=my_data;

The random number between 1 and 10 turned out to be 9.

Note that we used the streaminit() function to ensure that this example is reproducible. This means that each time we run this code, the random number will be 9.

Feel free to leave out the streaminit() function to produce a different random value each time you run the code.

Example 2: Generate Variable with Several Random Numbers

The following code shows how to generate a variable in SAS that contains 10 random values between 1 and 20:

/*create dataset with variable that contain random value*/
data my_data;
   call streaminit(10);
   do i = 1 to 10;
   x = rand("integer", 1, 20);
   output;
   end;
run;

/*view dataset*/
proc print data=my_data;

Notice that each of the values for the variable x are random integers between 1 and 20.

Example 3: Generate Multiple Variables with Several Random Numbers

The following code shows how to generate multiple variables in SAS that contain random values:

/*create dataset with variable that contain random value*/
data my_data;
   call streaminit(10);
   do i = 1 to 10;
   x = rand("integer", 1, 20);
   y = rand("integer", 50, 100);
   output;
   end;
run;

/*view dataset*/
proc print data=my_data;

The x variable contains 10 random integers between 1 and 20 while the y variable contains 10 random integers between 50 and 100.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Normalize Data in SAS
How to Rename Variables in SAS
How to Remove Duplicates in SAS
How to Replace Missing Values with Zero in SAS

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories