Is there a straightforward way in dplyr to expand a dataframe by replicating a row based on a specific vector?
For example, I have following dataframe:
df <- tibble(Year=c(2019),
cat1=c("A","B"),
cat2=c("X","Y"),
value1=c(1,2),
value2=c(10,20))
selected_years <- c(2019:2021)
where I would like to replicate the row where cat1=="A" for the years 2019-2021. The values of some columns (value1, cat) should be taken from the original year 2019, some other columns (value2) filled with NAs.
The final output should look like:
Year cat value1 value2
2019 A 1 10
2020 A 1 NA
2021 A 1 NA
2019 B 2 20
I tried with bind_rows()...however, the result is not fully what I wanted (I only get the "A"-Part not the "B"-Part), and I am not sure if this is really the most intuitive/dplyr way to go, or if another approach (or even specific function) would be more reasonable:
df%>%
filter(cat1=="A",Year==2019)%>%
bind_rows(
data.frame(
Year=setdiff(selected_years,.$Year),
cat1=.$cat1,
value1=.$value1
)
)
)
Edit:
I also tried using expand and right_join, but I then my desired column values are not repeated:
df %>%
dplyr::right_join(df %>%
filter(cat1=="A",Year==2019)%>%
expand(Year=c(2019:2021)))
Maybe an approach involving case_when?