Menu
CoddyTech

向量化 ifelse()

本课属于 Coddy R 学习旅程的“逻辑与流程”单元。第 48 课,共 64 课。

if 用于测试一个条件。如果给定的向量包含多个值,它会因错误 the condition has length > 1 而停止运行。ifelse(test, yes, no) 会逐个处理元素,并为每个元素返回一个结果:

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

输出:

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

yes 和 no 可以是长度相同的向量,因此每个元素都可以得到各自计算出的值:

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

输出:

[1]  40 108  75

如果结果超过两种,就嵌套调用 ifelse()。系统会按顺序检查每个元素的条件:

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

输出:

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

ifelse() 适用于创建新的数据框列,让每一行都有自己的标签:

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

输出:

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

挑战

简单

完成 shipping(weights)。返回每个包裹的运费,并用 , 连接:重量不超过 1 kg 的包裹运费为 4,不超过 5 kg 的包裹运费为 9,更重的包裹每 kg 运费为 2。使用 ifelse(),不要使用循环。

提供的代码会读取一行以逗号分隔的重量,并打印返回值。

亲手试试

shipping <- function(weights) {
  # 在这里编写你的代码
  ""
}

# 提供的输入和输出代码:保持原样
input <- suppressWarnings(readLines(file("stdin")))
cat(shipping(as.numeric(strsplit(input[1], ",")[[1]])), sep = "\n")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: R 在线编译器