There are many Q&As concerning the use of purrr package functions with mutate, but I haven't found one that I can apply to my particular situation, which involves a conditional function. Here's an example with a toy dataframe:
library(dplyr)
df <- tibble(year = c("2018", "2018", "2019", "2019"),
observed = c("YES", "NO", "NO", "YES"))
Here's the desired output:
df %>% mutate(observed_2018 = if_else(observed == "YES" & year == "2018", 1, 0),
observed_2019 = if_else(observed == "YES" & year == "2019", 1, 0))
#> # A tibble: 4 × 4
#> year observed observed_2018 observed_2019
#> <chr> <chr> <dbl> <dbl>
#> 1 2018 YES 1 0
#> 2 2018 NO 0 0
#> 3 2019 NO 0 0
#> 4 2019 YES 0 1
How can I programmatically generate observed_2018 and observed_2019 using a purrr function (or, alternatively, across())?