本文介绍了从星期一开始每周将数据汇总到每周级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的数据框,

I have a data frame like,

2015-01-30     1       Fri
2015-01-30     2       Sat
2015-02-01     3       Sun
2015-02-02     1       Mon
2015-02-03     1       Tue
2015-02-04     1       Wed
2015-02-05     1       Thu
2015-02-06     1       Fri
2015-02-07     1       Sat
2015-02-08     1       Sun

我想将它聚合到每周级别,这样每周都从星期一"开始,到星期日"结束.因此,在上述汇总数据中,第一周应在 2015-02-01 结束.

I want to aggregaate it to weekly level such that every week starts from "monday" and ends in "sunday". So, in the aggregated data for above, first week should end on 2015-02-01.

输出应该看起来像上面的东西

output should look like something for above

firstweek    6
secondweek   7

我试过了,

data <- as.xts(data$value,order.by=as.Date(data$interval))
weekly <- apply.weekly(data,sum)

但是这里的最终结果,每周都是从星期日开始的.

But here in the final result, every week is starting from Sunday.

推荐答案

有了 dplyrlubridate 这真的很简单,感谢函数 isoweek

Wit dplyr and lubridate is this really easy thanks to the function isoweek

my.df <- read.table(header=FALSE, text=
  '2015-01-30     1       Fri
   2015-01-30     2       Sat
   2015-02-01     3       Sun
   2015-02-02     1       Mon
   2015-02-03     1       Tue
   2015-02-04     1       Wed
   2015-02-05     1       Thu
   2015-02-06     1       Fri
   2015-02-07     1       Sat
   2015-02-08     1       Sun')
 my.df %>% mutate(week = isoweek(V1)) %>% group_by(week) %>% summarise(sum(V2))

或者更短一点

my.df %>% group_by(isoweek(V1)) %>% summarise(sum(V2))

这篇关于从星期一开始每周将数据汇总到每周级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-14 01:31