用于标记超差参数值的剪切函数

cut function for to label out-of-tolerance parameter values

工艺参数有上限和下限。当数据被收集并存储在向量中时,我尝试使用 cut 函数重新编码向量。

我是怎么做到的(举个例子):

x = mtcars$mpg

cut(x, breaks = c(-Inf,20, 30, Inf), labels = c("low","good","high"))

效果很好。

但是当我试图将过高和过低的值标记为 "failure" 时,会出现一条错误消息:

x = mtcars$mpg

cut(x, breaks = c(-Inf,20, 30, Inf), labels = c("failure","pass","failure"))

Error in `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  : factor level [3] is duplicated

显然 cut 函数不希望我们提供重复的标签。

有什么解决方法吗?

从您使用 cut 的方式开始,您只需重新编码值即可。

x = mtcars$mpg
F1 = cut(x, breaks = c(-Inf,20, 30, Inf), labels = c("low","good","high"))
F2 = factor(ifelse(F1=="good", "pass", "failure"))

如果您想继续使用 cut,一种选择是更改 cut

之后的 levels
x1 <- cut(x, breaks = c(-Inf,20, 30, Inf), labels = c("low","good","high"))
levels(x1) <- c("failure","pass","failure")

但是,您可以使用简单的 ifelse

而不是 cut
ifelse(x >= 20 & x <= 30, "pass", "failure")

或者只是

c("failure", "pass")[(x >= 20 & x <= 30) + 1]

或者,如果有多个条件需要检查,我们可以使用 dplyr 中的 case_when,如果需要,我们可以在其中添加条件。

library(dplyr)
mtcars %>%
  mutate(result = case_when(mpg >= 20 & mpg <= 30 ~ "pass", 
                            TRUE ~ "failure"))