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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With