【问题标题】:Finding a mean value of velocity by month (using R)按月查找速度的平均值(使用 R)
【发布时间】:2015-05-21 17:02:24
【问题描述】:

我这里有数据表:

row      V1      velocity

1   2009-04-06  95.9230769230769

2   2009-04-11  95.0985074626866

3   2009-04-17  95.8064935064935

4   2009-04-22  94.6357142857143

5   2009-04-27  95.3626865671642

6   2009-05-03  95.9101265822785

7   2009-05-08  95.826582278481

8   2009-05-14  94.5126582278481

9   2009-05-20  95.8371428571429

10  2009-05-25  94.6981481481481

11  2009-05-30  96.397619047619

12  2009-06-05  94.8132530120482

13  2009-06-10  96.4558139534884

14  2009-06-16  94.9627906976744

15  2009-06-21  95.2666666666667

16  2009-06-26  95.2919540229885

17  2009-07-01  95.4333333333333

18  2009-07-07  95.3375

19  2009-07-12  95.0534246575343

20  2009-07-18  96.0277777777778

21  2009-07-24  95.6885057471264

22  2009-07-29  93.9375

23  2009-08-03  95.2776315789474

24  2009-08-08  94.9089285714286

25  2009-08-13  96.8906976744186

26  2009-08-19  95.4487804878049

27  2009-08-24  97.2444444444444

28  2009-08-30  95.1174418604651

我想编写一个 r 代码来按月计算速度的平均值。 (有五月、六月、七月和八月。

我能做什么?

【问题讨论】:

  • 响应速度让我着迷。谢谢!

标签: r date average subset


【解决方案1】:

或者只是:

tapply(df$velocity, months(as.Date(df$V1)), mean)
   April   August     Juli     Juni      Mai 
95.36530 95.81465 95.24634 95.35810 95.53038 

【讨论】:

  • aggregate(velocity ~ as.POSIXlt(V1)$mon, df, mean)aggregate(velocity ~ months(as.Date(df$V1)), df, mean)
【解决方案2】:

我会这样做

使用lubridate 创建月份变量以在dplyr 中分组,然后获取平均值。

library(lubridate)
library(dplyr)

df %>% group_by(month = month(df$V1)) %>% summarize(mean = mean(velocity))

         month     mean
1            4 95.36530
2            5 95.53038
3            6 95.35810
4            7 95.24634
5            8 95.81465

如果你添加 label=T 你会得到这个:

df %>% group_by(month = month(df$V1,label=T)) %>% summarize(mean = mean(velocity))

  month     mean
1   Apr 95.36530
2   May 95.53038
3   Jun 95.35810
4   Jul 95.24634
5   Aug 95.81465

【讨论】:

  • 如果你在基础 R 中有相同的功能,你为什么要加载 lubridate
猜你喜欢
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2021-01-30
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多