【发布时间】:2020-09-23 17:31:38
【问题描述】:
我正在尝试在长格式数据结构中提取组的一个值,并将其分散到一列中。最好用一个例子来解释。请参阅下面的示例数据。在这种情况下,我想提取 c 的值并根据数据中存在的分组将其复制到新列中。
我正在寻找一种优雅的方式来实现这一点,尤其是tidyverse 解决方案将是理想的。
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
这是预期的输出:
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
还有数据:
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"
))
编辑:
我确实想出了一个两部分的解决方案,但我仍然认为有更好的方法。
lookup <- df %>%
group_by(year, month, location) %>%
filter(group == "c") %>%
summarize(c_value = value)
df %>%
left_join(lookup, by = c("year", "month", "location"))
【问题讨论】: