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!

Kim
  • 3,463
  • 2
  • 26
  • 48
Sal
  • 61
  • 6
  • 2
    Can you show a small reproducible example. The error message says that all those arguments may not have the same length. Are those columns in the data? i.e. open_flag, open, click_flag, mirror_flag etc? – akrun Apr 01 '22 at 21:34
  • 1
    should it be `TRUE ~ open_flag`? – langtang Apr 01 '22 at 21:44
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. That error seems oddly unrelated to the code you've shown. It would be helpful if we could recreate it to see what's going on. – MrFlick Apr 01 '22 at 21:44

1 Answers1

0

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)
)
Kim
  • 3,463
  • 2
  • 26
  • 48
langtang
  • 11,276
  • 10
  • 25
  • 1
    Thanks for your answer. In fact, I did find this issue out and fixed it in my code, but I still got the same error. Anyway, I am going to mark this as answer given the provided code in the question. I will post another question regarding the persistent issue if I can mock up a data set similar to the one that I am working on, which is confidential. – Sal Apr 11 '22 at 18:10
  • No. Even if `open` column exists, the error can happen if the responses to each "case" are not of the same class (e.g., character vs. factor) – Kim Apr 30 '22 at 05:46