BudiBadu Logo
Samplebadu

R by Example: Conditionals

R 4.x

Implementing decision logic with this sample code demonstrating if-else statements for scalar conditions, vectorized ifelse function for element-wise conditionals, switch statement for multiple options, and logical operator usage.

Code

x <- 5

# Standard if-else
if (x > 0) {
  print("Positive")
} else if (x < 0) {
  print("Negative")
} else {
  print("Zero")
}

# Vectorized conditional: ifelse()
# ifelse(test, yes, no)
nums <- c(-2, -1, 0, 1, 2)
signs <- ifelse(nums >= 0, "Positive", "Negative")
print(signs) 
# "Negative" "Negative" "Positive" "Positive" "Positive"

# Switch statement
type <- "mean"
val <- switch(type,
              "mean" = mean(nums),
              "median" = median(nums),
              "sum" = sum(nums))

Explanation

The if and else statements control program flow based on logical conditions that must evaluate to a single TRUE or FALSE value. When a vector of length greater than 1 is passed to if, R issues a warning and uses only the first element. Conditions can use comparison operators ==, !=, <, >, <=, >= and logical operators &, |, ! for combining conditions.

For vectorized conditionals operating on entire vectors element-wise, R provides the ifelse() function. It takes three arguments: a logical vector test, a value to return for TRUE elements, and a value for FALSE elements. The function returns a vector of the same length as the test vector, applying the conditional logic to each element independently. This is essential for data recoding and transformation operations on vectors and data frame columns.

The switch() function provides cleaner syntax than long if-else if chains when selecting one of several options based on a value. It takes an expression (typically a string or integer) and named arguments representing possible values and their corresponding return values. For character matching, switch() returns the value associated with the matching name, while for numeric input it returns the value at that position.

Code Breakdown

4
if (x > 0) evaluates single logical condition for scalar value.
15
ifelse(nums >= 0, ...) applies condition element-wise to entire vector.
21
switch(type, ...) selects value based on matching name or position.
22-24
Named arguments in switch provide option-value pairs for selection.