【问题标题】:Weird error message when using mutate()/case_when()使用 mutate()/case_when() 时出现奇怪的错误消息
【发布时间】:2021-05-30 17:44:22
【问题描述】:

我正在尝试使用 mutate/case_when 在 R 中创建一个新变量,但遇到了一个奇怪的错误。如果我运行这段代码:

library(tidyverse)
df <- data.frame(dist = c(rep(seq(-50,50,1), each = 50)))
temp <- df %>%
  mutate(bins = case_when(dist>=-50 & dist<-40 ~ -45,
                          dist>=-40 & dist<-30 ~ -35,
                          dist>=-30 & dist<-20 ~ -25,
                          dist>=-20 & dist<-10 ~ -15,
                          dist>=-10 & dist<0 ~ -5,
                          dist>=0 & dist<10 ~ 5,
                          dist>=10 & dist<20 ~ 15,
                          dist>=20 & dist<30 ~ 25,
                          dist>=30 & dist<40 ~ 35,
                          dist>=40 ~ 45))

我收到此错误消息:

Error: Problem with `mutate()` input `bins`.
x could not find function "&<-"
ℹ Input `bins` is `case_when(...)`.
Run `rlang::last_error()` to see where the error occurred.

有人知道为什么会这样吗?我经常使用 mutate/case_when 并且从未见过这样的东西。

【问题讨论】:

  • &lt;- 符号之间添加一个空格(即&lt; -),以便将它们解释为“小于负x”而不是“将x 分配给dist”。
  • 这解决了它,我明白现在发生了什么——非常感谢!

标签: r tidyverse dplyr


【解决方案1】:

为什么不简单地这样做(仅使用单边条件,case_when 将评估它,优先考虑以前的条件)

temp <- df %>%
  mutate(bins = case_when(dist < -40 ~ -45,
                          dist < -30 ~ -35,
                          dist < -20 ~ -25,
                          dist < -10 ~ -15,
                          dist < 0 ~ -5,
                          dist < 10 ~ 5,
                          dist < 20 ~ 15,
                          dist < 30 ~ 25,
                          dist < 40 ~ 35,
                          dist >= 40 ~ 45))

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2020-02-05
    相关资源
    最近更新 更多