在数组中添加平均列

时间:2013-04-09 13:58:45

标签: r statistics dataframe average

我每小时收集一个data.frame中的本地温度,其中包含3列和R中的多行(1000+):

日 - 小时 - 温度

  • 1 - 11:00 - 14
  • 1 - 12:00 - 17
  • ...
  • 2 - 11:00 - 10
  • 2 - 12:00 - 19
  • ...
  • 3 - 11:00 - 15
  • 3 - 12:00 - 9

我需要添加一个新列,其中包含每小时间隔内的平均温度。 在这个例子中:平均温度在11:00等于13ºC,在12:00等于15C,所以我需要:

日 - 小时 - 温度 - 平均值

  • 1 - 11:00 - 14 - 13
  • 1 - 12:00 - 17 - 15
  • ...
  • 2 - 11:00 - 10 - 13
  • 2 - 12:00 - 19 - 15
  • ...
  • 3 - 11:00 - 15 - 13
  • 3 - 12:00 - 9 - 15

我试过cbind,聚合但是我失败了。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果df是您的data.frame,则以下内容可能有效:

  avgTemp <- sapply(unique(df$Hour),function(x){mean(df$Temperature[df$Hour==x])})
  names(avgTemp) <- unique(df$Hour)

  df <- cbind(df,avgTemp[df$Hour])