r - Calculate difference from the group mean using dplyr
问题描述
I want to calculate the difference each row has from its group's mean. Is there a way to do this without creating an intermediate table and joining it?
group_summary <- mtcars %>%
group_by(cyl) %>%
summarize(mean_mpg = mean(mpg))
left_join(mtcars, group_summary) %>%
mutate(mpg_diff_from_group = mpg - mean_mpg)
解决方案
Yes, the following works without intermediate table:
mtcars %>%
group_by(cyl) %>%
mutate(grouped_diff = mpg - mean(mpg)) %>%
ungroup()
推荐阅读
- r - validObject(.Object) 中的错误:无效类“dsparseModelMatrix”对象:超类“Mnumeric”
- ios - 在我自己的 pod 库上添加 pod 或 Swift 包管理器
- python-3.x - 无法将系列转换为
- python - Django 无法保存子对象的父 ID
- javascript - 如何使用 React js 动态过滤产品
- javascript - how to make the slider function as it should?
- python - 随机池化层的实现
- jquery-select2 - select2 在字段集元素内不起作用
- typescript - 类型转换表达式预计在 vue+ts 的 eslint 中用括号包裹
- rabbitmq - 带有 RabbitMq 的 Mqtt - 连接数远远多于通道数