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 75Nest 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 availableChallenge
EasyComplete 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart10Advanced Control Flow
The switch() FunctionVectorized ifelse()repeat and breakRecursive FunctionsRecap - Grade Classifier2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler