如何结合多个总结呼叫dplyr?
鉴于DF,
ww <- data.frame(
GM = c("A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B",
"C", "C", "C", "C", "C", "C"),
stanza = rep(c("Past", "Mid", "End"), 6),
change = c(1, 1.1, 1.4, 1, 1.3, 1.5, 1, 1.2, 1.4,
1.1, 1.2, 1.3, .9, 1.2, 1.3, .9, 1.3, 1.5))
我想计算每个GM的过去平均值,并根据GM特定的均值来计算“变化”中的每个值。我可以使用两个dplyr调用和一个连接函数进行以下操作:
past <- ww %>%
group_by(GM) %>%
filter(stanza == "Past") %>%
summarize(past.mean = mean(change))
ww <- left_join(ww, past, by = "GM")
ww %>%
group_by(GM, stanza) %>%
summarize(pr.change = change/past.mean)
但是必须有一种在一个dplyr调用中进行此操作的方法。
Given the df
ww <- data.frame(
GM = c("A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B",
"C", "C", "C", "C", "C", "C"),
stanza = rep(c("Past", "Mid", "End"), 6),
change = c(1, 1.1, 1.4, 1, 1.3, 1.5, 1, 1.2, 1.4,
1.1, 1.2, 1.3, .9, 1.2, 1.3, .9, 1.3, 1.5))
I would like to calculate the mean for Past for each GM and the divide each value in 'change' by the GM specific mean. I can do this with two dplyr calls and a join function as follows:
past <- ww %>%
group_by(GM) %>%
filter(stanza == "Past") %>%
summarize(past.mean = mean(change))
ww <- left_join(ww, past, by = "GM")
ww %>%
group_by(GM, stanza) %>%
summarize(pr.change = change/past.mean)
But there must be a way to do this in one dplyr call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
data.table
解决方案:A
data.table
solution:无需加入,您可以直接在一个管道中计算它:
输出
No need to join, you can compute this directly in one pipe chain:
Output
continue
Using
base R
-output