I have this data set about cows. I have calving dates and dry-off dates with some dates in between with no such events. The dates in between are irregular, meaning that there may be gaps. It looks about like this:
ID <- c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B")
date <- c("2022-01-01", "2022-01-05", "2022-01-06", "2022-01-07", "2022-01-10", "2022-01-12",
"2022-01-13", "2022-01-16", "2022-01-17", "2022-01-18",
"2022-02-01", "2022-02-05", "2022-02-06", "2022-02-07", "2022-02-10", "2022-02-12",
"2022-02-13", "2022-02-16", "2022-02-17", "2022-02-18")
event <- c("calved", "NA", "NA", "NA", "dry-off", "NA", "NA", "calved", "NA", "NA",
"calved", "NA", "NA", "NA", "dry-off", "NA", "calved", "NA", "NA", "NA")
df <- data.frame(ID, date, event)
df$date <- as.Date(df$date)
What I want is a new column where the day of calving is "1" and then the days since calving (days in milk = DIM) are shown. Then, I want the day of dry-off as "0" and all the days the cow is dry until calving also as "0" The data frame would look like this:
DIM <- c("1", "5", "6", "7", "0", "0", "0", "1", "2", "3",
"1", "5", "6", "7", "0", "0", "1", "4", "5", "6")
what_I_want <- data.frame(ID, date, event, DIM)
I can do the "1" and "0" with this:
df1 <- df %>%
mutate(DIM = case_when(str_detect(event, "calved") ~ "1",
str_detect(event, "dry-off") ~ "0",
TRUE ~ ""))
But then I'm stuck. Thank you for your help!