Let's say I have a data.frame df:
#fake dataset
id <- c(1,2,3,4,5,6,7,8,9,10,11,12,13)
loc <- c(1,1,2,2,2,3,3,3,3,3,3,3,3)
date <- c(2021, 2022, 2021, 2021, 2022, 2021, 2021, 2022, 2023, 2023, 2023, 2023, 2023)
hab <- c("w", "l", "w", "w", "w", "l", "l", "w", "w", "w", "w", "w", "w")
spec <- c("frog", "frog", "frog", "frog", "frog", "beaver", "beaver", "beaver", "kingfisher", "kingfisher", "kingfisher", "kingfisher", "kingfisher")
df <- data.frame(id, loc, date, hab, spec)
I want to send rows of df down different logic branches. In each branch I might reassign values of existing columns or create new columns. Easy enough to do in dplyr with mutate(), if_else() and case_when(). But this becomes cumbersome as I end up repeating the same condition for each column assignment I want to do and dplyr has to check the same condition for each column assignment.
My sense is that the solution looks something like this:
# conditional branch for loc == 1 & spec == "frog"
df_tmp <- df %>%
filter(loc == 1 & spec == "frog") %>%
mutate(Date = 2025,
x = 1)
# remerge with original df
df <- df %>%
left_join(df_tmp, by=join_by("id"))
# id loc.x date.x hab.x spec.x loc.y date.y hab.y spec.y x
# 1 1 1 2021 w frog 1 2025 w frog 1
# 2 2 1 2022 l frog 1 2025 l frog 1
# 3 3 2 2021 w frog NA NA <NA> <NA> NA
# 4 4 2 2021 w frog NA NA <NA> <NA> NA
# 5 5 2 2022 w frog NA NA <NA> <NA> NA
# 6 6 3 2021 l beaver NA NA <NA> <NA> NA
# 7 7 3 2021 l beaver NA NA <NA> <NA> NA
# 8 8 3 2022 w beaver NA NA <NA> <NA> NA
# 9 9 3 2023 w kingfisher NA NA <NA> <NA> NA
# 10 10 3 2023 w kingfisher NA NA <NA> <NA> NA
# 11 11 3 2023 w kingfisher NA NA <NA> <NA> NA
# 12 12 3 2023 w kingfisher NA NA <NA> <NA> NA
# 13 13 3 2023 w kingfisher NA NA <NA> <NA> NA
However, I want a data.frame that does not have repeated columns and NAs populated for unaffected rows that looks like this:
# id loc date hab spec x
# 1 1 1 2025 w frog 1
# 2 2 1 2025 l frog 1
# 3 3 2 2021 w frog NA
# 4 4 2 2021 w frog NA
# 5 5 2 2022 w frog NA
# 6 6 3 2021 l beaver NA
# 7 7 3 2021 l beaver NA
# 8 8 3 2022 w beaver NA
# 9 9 3 2023 w kingfisher NA
# 10 10 3 2023 w kingfisher NA
# 11 11 3 2023 w kingfisher NA
# 12 12 3 2023 w kingfisher NA
# 13 13 3 2023 w kingfisher NA