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

  • 本文关键字:向量 case 错误 出错 dplyr 属性 when r
  • 更新时间 :
  • 英文 :


我正在dplyr链中运行以下case_when

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

上述所有变量都属于int类型。然而,我得到了这个消息:

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

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

注意:我可以使用ifelse()来解决这个问题,但我真的很想知道如何为case_when()语句解决它!

我收到了同样的错误消息,并挠头了15分钟。这是由于尝试将integernumeric类型结合在一起。这是一个可重复的例子。

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

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

创建于2022-08-03由reprex包(v2.0.1(

我认为您需要将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.

正确:

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

输入:

d <- data.frame(
open_flag = c(0, 2, 0),
click_flag = c(-1, 0, 1),
mirror_flag = c(0, 0, 3)
)