Menu
Coddy logo textTech

Vectorized ifelse()

Part of the Logic & Flow section of Coddy's R journey. Lesson 48 of 64.

if tests one condition. Given a vector of several values it stops with the error the condition has length > 1. ifelse(test, yes, no) works element by element and returns one result per element:

temps <- c(12, 25, 31, 18)
print(ifelse(temps > 20, "warm", "cool"))

Output:

[1] "cool" "warm" "warm" "cool"

yes and no can be vectors of the same length, so each element can get its own computed value:

price <- c(40, 120, 75)
final <- ifelse(price > 100, price * 0.9, price)
print(final)

Output:

[1]  40 108  75

Nest ifelse() calls for more than two outcomes. The conditions are checked in order for each element:

scores <- c(95, 72, 48, 81)
grade <- ifelse(scores >= 90, "A", ifelse(scores >= 70, "B", "C"))
print(grade)

Output:

[1] "A" "B" "C" "B"

ifelse() is useful for a new data frame column, where every row needs its own label:

df <- data.frame(item = c("tea", "oil"), stock = c(0, 8))
df$status <- ifelse(df$stock == 0, "sold out", "available")
print(df)

Output:

  item stock    status
1  tea     0  sold out
2  oil     8 available
challenge icon

Challenge

Easy

Complete shipping(weights). Return the shipping cost of each parcel, joined with , : parcels up to 1 kg cost 4, up to 5 kg cost 9, and heavier parcels cost 2 per kg. Use ifelse(), not a loop.

The supplied code reads the weights as a comma-separated line and prints the returned value.

Try it yourself

shipping <- function(weights) {
  # Write your code here
  ""
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(shipping(as.numeric(strsplit(input[1], ",")[[1]])), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler