Program generates a random number from a normal distribution using if-else (Nested Statement)

1–2 minutes

read

This R program involves nested if-else statements to check conditions:

  • 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 enters the outer if-else statement:
    • If random_numbers is greater than 1:
      • The inner if-else statement is not executed.
      • number <- "Number is greater than 1": The variable number is assigned the string value “Number is greater than 1”.
  • If random_numbers is not greater than 1:
    • The program enters the inner if-else statement:
      • 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 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 checks its value against multiple conditions. Depending on the value of random_numbers, it assigns different messages to the variable number accordingly.

Nested if-else statements in R helps you to test multiple conditions within each other and is a way to include one if-else statement inside another.

Leave a comment