How to use the ifelse statement in the R language?

In R language, the ifelse() function can be used to select different values based on a given condition. Its syntax is as follows:

This is equivalent to “if the test is true, then do ‘yes’, otherwise do ‘no'”.

  1. Test: A logical condition that, if true, returns the value “yes,” otherwise returns the value “no.”
  2. yes: the value returned when the condition is TRUE.
  3. No: the value returned when the condition is FALSE.

Here is a basic example:

x <- 10

result <- ifelse(x > 5, "x大于5", "x小于等于5")
print(result)

# 输出结果为 "x大于5"

In this example, if x is greater than 5, it will return the string “x is greater than 5”; otherwise, it will return the string “x is less than or equal to 5”.

It is worth noting that the ifelse() function can operate on vectors, returning a vector that matches the condition. Therefore, conditional statements can be made based on multiple conditions within a vector. Here is an example:

x <- c(1, 2, 3, 4, 5)

result <- ifelse(x > 3, "大于3", "小于等于3")
print(result)

# 输出结果为 "小于等于3" "小于等于3" "小于等于3" "大于3" "大于3"

In this example, based on the relationship between the value of each element in vector x and 3, return the corresponding string.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds