Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this case_when command do the command for all cases?

4 in column 1 represents an answer that means "other". Column 2 represents what that "other" is. I want everything that doesn’t have answer 4 in column 1 to have NA in column 2. Using case_when does not give the result I expect.

I have this data

col1    col2
1       "a"
4       "c"
4       NA
3       NA

I run:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df <- df %>%
  mutate(col2 = case_when(col1 != 4 ~ NA))

And expect:

col1    col2
1       NA
4       "c"
4       NA
3       NA

But I get

col1    col2
1       NA
4       NA
4       NA
3       NA

What did I do wrong?

>Solution :

The issue is that your case_when has no case for col2 == 4. Therefore NA is returned. According to the docs:

If no cases match, NA is returned.

To fix that add a default value via TRUE ~ col2 to your case_when:

df <- data.frame(
  col1 = c(1, 4, 4, 3),
  col2 = c("a", "c", NA, NA)
)

library(dplyr)

df %>%
  mutate(col2 = case_when(
    col1 != 4 ~ NA_character_, 
    TRUE ~ col2))
#>   col1 col2
#> 1    1 <NA>
#> 2    4    c
#> 3    4 <NA>
#> 4    3 <NA>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading