使用 mtcars 数据汇总 table 气缸与居中(mpg)
Using mtcars data to make a summarised table of cylinders versus centered(mpg)
Bare with me...我正在使用 R/RStudio 和数据 mtcars, dplyr 、mutate 和 summarise 命令。还尝试了 group by.
我想将值居中 mtcars$mpg 然后获取该信息并显示 汽缸数与居中 mtcars$mpg[=42 的摘要=].
到目前为止...
mtcars %>% mutate(centered_mpg = mpg - mean(mpg, na.rm = TRUE)) %>% summarise(centered_mpg, cyl)
以上产生:
centered_mpg
cyl
0.909375
6
0.909375
6
2.709375
4
1.309375
6
...
...
相反,我想要:
centered_mpg
cyl
x1
4
x2
6
x3
8
你在找这个吗?
with(mtcars, aggregate(list(centered_mpg=scale(mpg, scale=FALSE)), list(cyl=cyl), mean))
# cyl centered_mpg
# 1 4 6.5730114
# 2 6 -0.3477679
# 3 8 -4.9906250
您似乎想通过减去全局 mean(mpg)
来使每辆汽车的 mpg
居中。这为每辆车提供了一个 centered_mpg
- 你的代码看起来很好。
然后您想按气缸组计算某种居中 mpg 值的“汇总”,因此我们需要 group_by(cyl)
然后定义您想要的任何汇总函数 - 这里我使用 mean()
但您可以使用 median
、sum
或您喜欢的任何其他内容。
mtcars %>%
mutate(centered_mpg = mpg - mean(mpg, na.rm = TRUE)) %>%
group_by(cyl) %>%
summarise(mean_centered_mpg = mean(centered_mpg))
# # A tibble: 3 x 2
# cyl mean_centered_mpg
# <dbl> <dbl>
# 1 4 6.57
# 2 6 -0.348
# 3 8 -4.99
Bare with me...我正在使用 R/RStudio 和数据 mtcars, dplyr 、mutate 和 summarise 命令。还尝试了 group by.
我想将值居中 mtcars$mpg 然后获取该信息并显示 汽缸数与居中 mtcars$mpg[=42 的摘要=].
到目前为止...
mtcars %>% mutate(centered_mpg = mpg - mean(mpg, na.rm = TRUE)) %>% summarise(centered_mpg, cyl)
以上产生:
centered_mpg | cyl |
---|---|
0.909375 | 6 |
0.909375 | 6 |
2.709375 | 4 |
1.309375 | 6 |
... | ... |
相反,我想要:
centered_mpg | cyl |
---|---|
x1 | 4 |
x2 | 6 |
x3 | 8 |
你在找这个吗?
with(mtcars, aggregate(list(centered_mpg=scale(mpg, scale=FALSE)), list(cyl=cyl), mean))
# cyl centered_mpg
# 1 4 6.5730114
# 2 6 -0.3477679
# 3 8 -4.9906250
您似乎想通过减去全局 mean(mpg)
来使每辆汽车的 mpg
居中。这为每辆车提供了一个 centered_mpg
- 你的代码看起来很好。
然后您想按气缸组计算某种居中 mpg 值的“汇总”,因此我们需要 group_by(cyl)
然后定义您想要的任何汇总函数 - 这里我使用 mean()
但您可以使用 median
、sum
或您喜欢的任何其他内容。
mtcars %>%
mutate(centered_mpg = mpg - mean(mpg, na.rm = TRUE)) %>%
group_by(cyl) %>%
summarise(mean_centered_mpg = mean(centered_mpg))
# # A tibble: 3 x 2
# cyl mean_centered_mpg
# <dbl> <dbl>
# 1 4 6.57
# 2 6 -0.348
# 3 8 -4.99