I'm trying to extract one value of a group in a long-format data structure, and spread it into a column. Best explained with an example. See sample data below. In this case, I want to extract the value for c and replicate it in a new column, based on the groupings present in the data.
I'm looking for an elegant way to achieve this, in particular a tidyverse solution would be ideal.
year month location group value
2019 1 top a 1
2019 1 top b 2
2019 1 top c 3
2019 1 bottom a 4
2019 1 bottom b 5
2019 1 bottom c 6
2019 2 top a 7
2019 2 top b 8
2019 2 top c 9
2019 2 bottom a 10
2019 2 bottom b 11
2019 2 bottom c 12
This is the expected output:
year month location group value c_value
2019 1 top a 1 3
2019 1 top b 2 3
2019 1 top c 3 3
2019 1 bottom a 4 6
2019 1 bottom b 5 6
2019 1 bottom c 6 6
2019 2 top a 7 9
2019 2 top b 8 9
2019 2 top c 9 9
2019 2 bottom a 10 12
2019 2 bottom b 11 12
2019 2 bottom c 12 12
And the data:
structure(list(year = c(2019, 2019, 2019, 2019, 2019, 2019, 2019,
2019, 2019, 2019, 2019, 2019), month = c(1, 1, 1, 1, 1, 1, 2,
2, 2, 2, 2, 2), location = c("top", "top", "top", "bottom", "bottom",
"bottom", "top", "top", "top", "bottom", "bottom", "bottom"),
group = c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a",
"b", "c"), value = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"
))
edit:
I did come up with a two part solution, but I still fell there is a better way.
lookup <- df %>%
group_by(year, month, location) %>%
filter(group == "c") %>%
summarize(c_value = value)
df %>%
left_join(lookup, by = c("year", "month", "location"))