Generate a random number from a normal distribution using if-else if – else (Chained Statements) in R programming

1–2 minutes

read

This R program involves an if-else statement with chained conditions to check multiple cases:

  • rm(number): This command removes any existing object named “number” from the R environment.
  • random_numbers <- rnorm(1): A single random number is generated from a standard normal distribution using the rnorm() function and stored in the variable random_numbers.
  • The program checks the value of random_numbers against multiple conditions:
    • If random_numbers is greater than 1:
      • number <- "Number is greater than 1": The variable number is assigned the string value “Number is greater than 1”.
  • Else, if random_numbers is greater than or equal to -1:
    • number <- "Number is between -1 and 1": The variable number is assigned the string value “Number is between -1 and 1”.
  • If none of the above conditions are met (i.e., random_numbers is less than -1):
    • number <- "Number is less than -1": The variable number is assigned the string value “Number is less than -1”.

In summary, this program generates a random number from a normal distribution and categorizes it into one of three ranges: greater than 1, between -1 and 1 (inclusive), or less than -1, based on the specified conditions. Chained if-else statements in R, also known as if-else-if statements, allow you to check multiple conditions sequentially.

Leave a comment