Conditioning using if_else and mutate

Hi guys I have data set with Hb values ,I want to find whether they are normal or not. As the refference ranges for each sex differs I want to write down it as conditionally. (If it is a female ,Hb below 12 is low and if male below 13.8 is low). Here is the code I used. This doesnot work

A <- anemia %>% if_else(Sex == "M") %>% mutate(Hb_level=case_when(Hb>13.7~ "Normal",Hb<13.8 ~"Low")), mutate(Hb_level=case_when(Hb>12~ "Normal",Hb<12 ~"Low"))

Please help anyone????

You didn't supply a reprex of your data, but below is a solution based on mock data that I think should work for your goal.

library(tidyverse)

set.seed(1)

hb <- tibble(
  sex = c(replicate(10, "M"), replicate(10, "F")),
  Hb = runif(length(sex), min = 7, max = 20)
)

hb %>% 
  mutate(hb_level = case_when(sex == "M" & Hb > 13.8 ~ "Normal",
                              sex == "F" & Hb > 12 ~ "Normal",
                              TRUE ~ "Low"))
#> # A tibble: 20 × 3
#>    sex      Hb hb_level
#>    <chr> <dbl> <chr>   
#>  1 M     10.5  Low     
#>  2 M     11.8  Low     
#>  3 M     14.4  Normal  
#>  4 M     18.8  Normal  
#>  5 M      9.62 Low     
#>  6 M     18.7  Normal  
#>  7 M     19.3  Normal  
#>  8 M     15.6  Normal  
#>  9 M     15.2  Normal  
#> 10 M      7.80 Low     
#> 11 F      9.68 Low     
#> 12 F      9.30 Low     
#> 13 F     15.9  Normal  
#> 14 F     12.0  Low     
#> 15 F     17.0  Normal  
#> 16 F     13.5  Normal  
#> 17 F     16.3  Normal  
#> 18 F     19.9  Normal  
#> 19 F     11.9  Low     
#> 20 F     17.1  Normal

Created on 2021-10-06 by the reprex package (v2.0.1)

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.