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
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