导入数据:
df <- read.table(text = "
Value ColA ColB ColC
0.8 0.3 0.7 1.1
0.1 0.2 0.7 1.3
0.7 0.5 0.8 1.0", header = T)
现在我们可以使用一组嵌套的
ifelse
-声明:
df$Category <-
ifelse(df$Value >= 0 & df$Value <= df$ColA, "Bottom",
ifelse(df$Value > df$ColA & df$Value <= df$ColB, "Middle",
ifelse(df$Value > df$ColB & df$Value <= df$ColC, "Top", NA)
)
)
输出:
> df
Value ColA ColB ColC Category
1 0.8 0.3 0.7 1.1 Top
2 0.1 0.2 0.7 1.3 Bottom
3 0.7 0.5 0.8 1.0 Middle
从…起
?ifelse
:
ifelse返回一个与test形状相同的值,该值由从yes或no中选择的元素填充,具体取决于test的元素是TRUE还是FALSE。
ifelse(test, yes, no)
另一种更具可读性的解决方案:
df$Category <- NA
df$Category[df$Value >= 0 & df$Value <= df$ColA] <- "Bottom"
df$Category[df$Value > df$ColA & df$Value <= df$ColB] <- "Middle"
df$Category[df$Value > df$ColB & df$Value <= df$ColC] <- "Top"
> df
Value ColA ColB ColC Category
1 0.8 0.3 0.7 1.1 Top
2 0.1 0.2 0.7 1.3 Bottom
3 0.7 0.5 0.8 1.0 Middle