dplyr case_when 抛出错误名称的属性 [1] 必须与向量 [0] 的长度相同

Sal*_*Sal 15 r

case_when我在链内运行以下命令dplyr

open_flag = case_when (
  open_flag == 0 & (click_flag > 0 | mirror_flag > 0) ~ 1,
  TRUE ~ open
)
Run Code Online (Sandbox Code Playgroud)

上面的所有变量都是类型int。然而,我收到了这条消息:

由名称(消息)错误引起 <- vtmp : ! “names”属性 [1] 的长度必须与向量 [0] 相同

我发现这篇文章(dplyr::case_when() 莫名其妙地返回名称(消息)<-`*vtmp*`错误)确定了问题。我不完全理解这个问题,所以我未能为我的case_when()上述问题应用解决方案!

注意:我可以使用 解决问题ifelse(),但我真的不知道如何解决该case_when()语句!

Art*_*hur 37

我收到了同样的错误消息并挠了挠头 15 分钟。这是由于尝试组合integernumeric类型。这是一个可重现的示例。

\n

这不是一个非常有用的错误消息:(

\n
library(tidyverse)\n\n# sample data\ndf <- tibble(\n  int_var  = 1:10,\n  real_var = as.numeric(1:10),\n  use_int  = c(rep(TRUE, 5), rep(FALSE, 5))\n)\n\n# error\ndf %>%\n  mutate(\n    new_var = case_when(\n      use_int ~ int_var,\n      TRUE    ~ real_var\n    )\n  )\n#> Error in `mutate()`:\n#> ! Problem while computing `new_var = case_when(use_int ~ int_var, TRUE ~\n#>   real_var)`.\n#> Caused by error in `` names(message) <- `*vtmp*` ``:\n#> ! \'names\' attribute [1] must be the same length as the vector [0]\n\n# fixed\ndf %>%\n  mutate(\n    new_var = case_when(\n      use_int ~ as.numeric(int_var),  # coerce to numeric\n      TRUE    ~ real_var\n    )\n  )\n#> # A tibble: 10 \xc3\x97 4\n#>    int_var real_var use_int new_var\n#>      <int>    <dbl> <lgl>     <dbl>\n#>  1       1        1 TRUE          1\n#>  2       2        2 TRUE          2\n#>  3       3        3 TRUE          3\n#>  4       4        4 TRUE          4\n#>  5       5        5 TRUE          5\n#>  6       6        6 FALSE         6\n#>  7       7        7 FALSE         7\n#>  8       8        8 FALSE         8\n#>  9       9        9 FALSE         9\n#> 10      10       10 FALSE        10\n
Run Code Online (Sandbox Code Playgroud)\n

由reprex 包于 2022 年 8 月 3 日创建(v2.0.1)

\n

  • 与上面的@MarkDavies类似,需要设置为“NA_real_”而不仅仅是“NA”才能为数字变量生成“~NA”赋值。 (2认同)

lan*_*ang 0

我相信你需要TRUE ~ open纠正TRUE ~ open_flag

错误:

d %>% 
  mutate(
    open_flag = case_when(
      open_flag == 0 & (click_flag > 0 | mirror_flag > 0) ~ 1,
      TRUE ~ open
    )
  )

Error in `mutate()`:
! Problem while computing `open_flag = case_when(...)`.
Caused by error in `` names(message) <- `*vtmp*` ``:
! 'names' attribute [1] must be the same length as the vector [0]
Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)

正确的:

d %>% 
  mutate(
    open_flag = case_when(
      open_flag == 0 & (click_flag > 0 | mirror_flag > 0) ~ 1,
      TRUE ~ open_flag
  )
)

  open_flag click_flag mirror_flag
1         0         -1           0
2         2          0           0
3         1          1           3

Run Code Online (Sandbox Code Playgroud)

输入:

d <- data.frame(
  open_flag = c(0, 2, 0),
  click_flag = c(-1, 0, 1),
  mirror_flag = c(0, 0, 3)
)
Run Code Online (Sandbox Code Playgroud)

  • 不会。即使存在“open”列,如果对每个“案例”的响应不属于同一类(例如,字符与因子),也会发生错误 (6认同)