本文介绍了从星期一开始,每周将数据汇总到每周级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,
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.
输出应类似于以上
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.
推荐答案
转换为日期并使用%W
格式以获取星期数...
Convert to date and use the %W
format to get a week number...
df <- read.csv(textConnection("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"), header=F, stringsAsFactors=F)
names(df) <- c("date", "something", "day")
df$date <- as.Date(df$date, format="%Y-%m-%d")
df$week <- format(df$date, "%W")
aggregate(df$something, list(df$week), sum)
这篇关于从星期一开始,每周将数据汇总到每周级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!