CASE_When error

I have a dataset df. The dput function yields
structure(list(Case_ID = 1:4, con_1 = c("afib", "HTN", "HL",
"diabe"), con_2 = c("anemia", "CAD", "HTN", "afib"), con_3 = c("stroke",
"HL", "CAD", "CAD"), con_4 = c("HL", "diabetes", "diabetes",
NA), con_5 = c("HTN", "stroke", "afib", NA)), class = "data.frame", row.names = c("1",
"2", "3", "4"))

I want to make a 5th column afib which should be equal to 1 if the con_1:5 has a case of afib or otherwise should be equal to 0.
I have tried this code

library(tidyr)

df<-df %>% mutate(afib = case_when(con_1=="afib"~"1"|con_2=="afib"~1|con_3=="afib"~"1"|con_4=="afib"~"1"|con_5=="afib"~"1" , TRUE ~ "0"))

however it gives me this error

Error: Problem with mutate() input afib.
x LHS of case 1 (con_1 == "afib" ~ "1" | con_2 == "afib" ~ 1 | con_3 == "afib" ~ "1" | con_4 =...) must be a logical vector, not a formula object.
i Input afib is case_when(...)

I know as per documentation of case_when LHS should be a logical vector, however I m new to R and do not know how to fix this error. Any help would be appreciated.

Is this what you want?


df %>% 
  mutate(afib = case_when(con_1=="afib"~"1",
                               con_2=="afib"~"1",
                               con_3=="afib"~"1",
                               con_4=="afib"~"1",
                               con_5=="afib"~"1",
                               TRUE ~ "0"))

  Case_ID con_1  con_2  con_3    con_4  con_5 afib
1       1  afib anemia stroke       HL    HTN    1
2       2   HTN    CAD     HL diabetes stroke    0
3       3    HL    HTN    CAD diabetes   afib    1
4       4 diabe   afib    CAD     <NA>   <NA>    1
1 Like

You fixed it my friend. Thank you for the help!

1 Like

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.