【问题标题】:average of multiple numbers in RR中多个数字的平均值
【发布时间】:2014-04-15 19:33:48
【问题描述】:

假设我用这段代码生成了一个数据

month<-c(rep(1,7),rep(2,7),rep(3,7))
date<-rep(c(rep(1,2),rep(2,3),rep(3,2)),3)
value<-rnorm(21)
df<-cbind(month,date,value))

所以现在我有这样的东西

      month date       value
 [1,]     1    1 -0.04256470
 [2,]     1    1 -2.50922102
 [3,]     1    2 -0.50458814
 [4,]     1    2 -1.00133322
 [5,]     1    2  0.70297514
 [6,]     1    3  0.79316448
 [7,]     1    3  0.66798947
 [8,]     2    1  1.60548790
 [9,]     2    1 -0.42484680
[10,]     2    2 -0.33906887
[11,]     2    2  1.02457883
[12,]     2    2  0.64175917
[13,]     2    3 -0.03832247
[14,]     2    3  0.86878829
[15,]     3    1  1.46691690
[16,]     3    1  0.77897932
[17,]     3    2 -1.02759643
[18,]     3    2  0.15902324
[19,]     3    2  1.36580741
[20,]     3    3 -1.70749048
[21,]     3    3  0.11327990

我将如何获取一个月内给定日期的平均值?

所以在这种情况下,我希望我的输出看起来像这样......

month date   avgvalue
1      1     -1.27589
1      2     -0.267649
1      3     0.66798947
2      1     0.590321
 ...

非常感谢您的帮助谢谢:)

【问题讨论】:

  • 如果您要提供可重现的样本,但又想使用随机数,最好在创建样本数据之前也使用set.seed()

标签: r aggregate average tapply


【解决方案1】:

你可以使用aggregate:

aggregate(df[,3], by=list(month=df[,1], date=df[,2]), mean)
#   month date          x
# 1     1    1  0.5661431
# 2     2    1  0.1843661
# 3     3    1  1.8339898
# 4     1    2  1.2053077
# 5     2    2 -0.2575551
# 6     3    2 -0.4464268
# 7     1    3 -0.7154689
# 8     2    3  0.7895702
# 9     3    3  0.4853081

【讨论】:

  • 公式方法在这里也很有效:aggregate(value ~ month + date, df, mean).
【解决方案2】:

您用tapply 标记了您的问题,所以这里是tapply 答案:

tapply(df[, "value"], INDEX=list(df[, "month"], df[, "date"]), FUN=mean)
#             1          2           3
# 1 -0.42965680  0.6943236  0.04505399
# 2  0.55021401 -0.3138895 -0.40966078
# 3  0.05676266  0.5212944  0.12521106

data.frame(as.table(
  tapply(df[, "value"], INDEX=list(df[, "month"], df[, "date"]), FUN=mean)))
#   Var1 Var2        Freq
# 1    1    1 -0.42965680
# 2    2    1  0.55021401
# 3    3    1  0.05676266
# 4    1    2  0.69432363
# 5    2    2 -0.31388954
# 6    3    2  0.52129439
# 7    1    3  0.04505399
# 8    2    3 -0.40966078
# 9    3    3  0.12521106

不过,更常见的方法是aggregate(提及)、plyr(提及)、data.table 和(最近)dplyrdata.tabledplyr 方法如下。

library(data.table)
DT <- data.table(df)
DT[, mean(value), by = list(month, date)]


library(dplyr)
DF <- data.frame(df)
DF %.% group_by(month, date) %.% summarise(mean(value))

更多更少常见的是ave + unique

unique(within(data.frame(df), {
  MV <- ave(value, month, date)
  rm(value)
}))

但它们都会把你带到同一个地方。

【讨论】:

  • 非常感谢您的详细解答!我喜欢所有不同的选择,尤其是因为我正在寻找最快的方法:)
【解决方案3】:
library("plyr")
df <- data.frame(df)
ddply(df, .(month,date), summarize, avgvalue=mean(value))

【讨论】:

  • 非常感谢!我喜欢这段代码比聚合代码运行得更快!
猜你喜欢
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 2022-01-13
  • 2019-04-01
  • 2017-02-06
相关资源
最近更新 更多