有人可以解释为什么只有部分数字被转换为高低字符串?
set.seed(1)
df <- data.frame(npitotal=ceiling(runif(30,0,40)))
df$npitotal[df$npitotal >= 22] <- "high"
df$npitotal[df$npitotal < 22] <- "low"
df$npitotal
# [1] "low" "low" "high" "high" "9" "high" "high" "high"
# [9] "high" "3" "9" "8" "high" "low" "high" "low"
#[17] "high" "high" "low" "high" "high" "9" "high" "6"
#[25] "low" "low" "low" "low" "high" "low"
答案 0 :(得分:2)
我最终的解决方案是在汽车套件中使用recode
:
library(car)
recode(df$npitotal,"0:21='low';22:40='high'")
注意0:21是[0,21](所以20.99评估为“低:在这种情况下)
感谢@Jay解释导致问题的原因:
进行第一次转换后,它变成了一个字符向量 - 所以第二次转换不是以数字方式进行评估,而是作为一个字符。