I am running the following case_when
inside a dplyr
chain:
open_flag = case_when (
open_flag == 0 & (click_flag > 0 | mirror_flag > 0) ~ 1,
TRUE ~ open
)
All variables above are of type int
. However, I get back this message:
Caused by error in names(message) <- vtmp : ! 'names' attribute [1] must be the same length as the vector [0]
I have found this post ( dplyr::case_when() inexplicably returns names(message) <- `*vtmp*` error ) that identified the issue. I don't fully understand the issue, and so I failed to apply a solution for my case_when()
above!
Note: I can solve the problem by using ifelse()
, but I really wonder how to solve it for the case_when()
statement!
I believe you need to correct TRUE ~ open
to TRUE ~ open_flag
:
ERROR:
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.
CORRECT:
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
Input:
d <- data.frame(
open_flag = c(0, 2, 0),
click_flag = c(-1, 0, 1),
mirror_flag = c(0, 0, 3)
)
I received this same error message and scratched my head for 15 minutes. It was due to trying to combine integer
and numeric
types. Here is a reproducible example.
It's not a very useful error message:(
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
Created on 2022-08-03 by the reprex package (v2.0.1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.