📜  ifelse in r (1)

📅  最后修改于: 2023-12-03 15:01:22.340000             🧑  作者: Mango

ifelse in r

ifelse is a common function used in R programming language that allows users to perform conditional operations on data.

Syntax

The syntax of ifelse function in R is:

ifelse(test_expression, yes_expression, no_expression)
  • test_expression is a logical vector to be tested
  • yes_expression is an expression to be evaluated if test_expression is TRUE
  • no_expression is an expression to be evaluated if test_expression is FALSE
Examples
# create a vector with random numbers
nums <- rnorm(10)

# using ifelse to replace values less than 0 with 0
ifelse(nums < 0, 0, nums)

# output:
# [1] 1.9647678 0.0000000 0.8963754 0.0000000 1.2692765 1.3437615
# [7] 0.0000000 0.7792927 1.1440523 0.0000000

The above example shows how ifelse can be used to replace values in a vector based on a condition.

# create two vectors
x <- c(5, 2, 9, 1, 7)
y <- c("Tom", "Jerry", "Bob", "Alice", "Kate")

# using ifelse to get the corresponding names based on values in x
ifelse(x > 5, y, "No match")

# output:
# [1] "No match" "No match" "Bob"      "No match" "Kate"

The above example shows how ifelse can be used to return values based on corresponding values in another vector.

Conclusion

ifelse is a useful function in R programming that allows users to perform conditional operations on data. Use it wisely to make your codes more efficient and organized.