看来dplyr::case_whendplyr::mutate调用中不像其他命令那样工作。例如:

library(dplyr)

case_when(mtcars$carb <= 2 ~ "low",
          mtcars$carb > 2 ~ "high") %>%
  table

作品:
.
high  low
  15   17

但是将case_when放在mutate链中:
mtcars %>%
  mutate(cg = case_when(carb <= 2 ~ "low",
                        carb > 2 ~ "high"))

你会得到:
 Error: object 'carb' not found

虽然这很好
mtcars %>%
  mutate(cg = carb %>%
           cut(c(0, 2, 8)))

最佳答案

0.7.0dplyr版本开始,case_whenmutate中起作用,如下所示:

library(dplyr) # >= 0.7.0
mtcars %>%
  mutate(cg = case_when(carb <= 2 ~ "low",
                        carb > 2  ~ "high"))

有关更多信息:http://dplyr.tidyverse.org/reference/case_when.html

关于r - case_when在突变管道中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38649533/

10-12 19:10