汇总R中的数据 [英] Aggregate data in R
本文介绍了汇总R中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个关于如何使用聚合
并在R中计算均值的简单例子。
I'm looking for a dead simple example on how to use aggregate
and calculate means in R.
说,我有以下数据框:
A B
100 85
200 95
300 110
400 105
我想计算某些范围的平均值结果如下:
And I want to calculate the mean values for some ranges with the following result:
RANGE MEAN
100-200 90
300-400 107.5
我该怎么做, cast()
或 aggregate()
?
推荐答案
假定您的数据框名为 x :
Assuming your data frame is named "x":
aggregate(x$B, list(cut(x$A, breaks=c(0, 200, 400))), mean)
# Group.1 x
# 1 (0,200] 90.0
# 2 (200,400] 107.5
使用 data.table,您可以执行以下操作:
With "data.table", you can do the following:
library(data.table)
as.data.table(x)[, .(RANGE = mean(B)), by = .(MEAN = cut(A, c(0, 200, 400)))]
# MEAN RANGE
# 1: (0,200] 90.0
# 2: (200,400] 107.5
这篇关于汇总R中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文