Make case_when / str_detect recognize NA as NA

In this df, a variable includes observations I want to rename as “lof”, “.”, “missense”. As there are many possibilities for the “missense”, I left it after TRUE (else) when using case_when function. The problem is the function is considering NA as “missense”. How can I tell this function to recognize NA as NA?


df <- df %>% 
  mutate(type_variant = case_when (str_detect(HGVSprot , regex("fs|Ter", ignore_case = TRUE)) ~ "LoF",
                                     str_detect(HGVSprot, "^\\.$") ~".",        
                                     TRUE ~"missense"))

I updated the case_when with is.na(HGVSprot) ~ NA, please check

Have tried, but it did not work

To make easier:

> HGVSprot <-  c("p.(Cys113Ter)","p.(Gln30His)","p.(Ser340Pro)", NA )
> V <- c("a", "b", "c", "d")
> df <- data.frame(HGVSprot, V)

Please try the below code it worked for me

df <- df %>% 
  mutate(type_variant = ifelse(!is.na(HGVSprot),case_when (str_detect(HGVSprot , regex("fs|Ter", ignore_case = TRUE)) ~ "LoF",
                                   str_detect(HGVSprot, "^\\.$") ~".",
                                   TRUE ~ "missense"), NA))

Worked just as perfect.

Good ideia adding ifelse. Thanks.

1 Like

thank you @Lilip, could you please consider this as a solution

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.