'dplyr case_when throws error names' attribute [1] must be the same length as the vector [0]

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!

r


Solution 1:[1]

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)
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kim