【发布时间】:2020-11-09 11:48:16
【问题描述】:
我尝试用 if 和 else if 语句解决以下问题:
- 如果“TRUE1”在“检查”列中明显,则选择带有“TRUE1”的行
- 如果“TRUE1”在“检查”列中不明显,则选择带有“TRUE2”的行,否则选择带有“TRUE3”的行
当“检查”列中的“TRUE1”和“TRUE2”可用时,以下代码似乎可以正常工作:
name <- c(1, 2, 3, 4, 5)
check <- c("TRUE1", "TRUE2", "TRUE3", "TRUE3", "TRUE3")
dataset <- data.frame(cbind(name, check))
> dataset
name check
1 1 TRUE1
2 2 TRUE2
3 3 TRUE3
4 4 TRUE3
5 5 TRUE3
slct_set <- if (dataset$check == "TRUE1") {
dataset[dataset[, "check"] == "TRUE1",]
} else if (dataset$check != "TRUE1") {
dataset[dataset[, "check"] == "TRUE2",]
} else {
dataset[dataset[, "check"] == "TRUE3",]
}
> slct_set
name check
1 1 TRUE1
但是,当我对整个“检查”列使用“TRUE3”时,会发生这种情况:
> dataset
name check
1 1 TRUE3
2 2 TRUE3
3 3 TRUE3
4 4 TRUE3
5 5 TRUE3
> slct_set <- slct_set <- if (dataset$check == "TRUE1") {
dataset[dataset[, "check"] == "TRUE1",]
} else if (dataset$check != "TRUE1") {
dataset[dataset[, "check"] == "TRUE2",]
} else {
dataset[dataset[, "check"] == "TRUE3",]
}
Warning messages:
1: In if (dataset$check == "TRUE1") dataset[dataset[, "check"] == "TRUE1", :
the condition has length > 1 and only the first element will be used
2: In if (dataset$check != "TRUE1") dataset[dataset[, "check"] == "TRUE2", :
the condition has length > 1 and only the first element will be used
> slct_set
[1] name check
<0 Zeilen> (oder row.names mit Länge 0)
我对 R 中的 if 语句很陌生,因此感谢任何帮助。
【问题讨论】:
-
if ... else ...语句未矢量化。这就是警告消息告诉您的内容。ifelse()函数是。这就是你需要的,它会给你正确的答案。
标签: r if-statement rows selection