将每日数据转换为每周

时间:2020-03-26 08:23:18

标签: r lubridate

我有一个数据集,其中包含来自商店销售的数据。所有这些数据均按从2017-01-03到2017-02-28期间的天数排序。您可以在下面的代码中看到数据。

Retail_data<-structure(list(Date = structure(c(17169, 17170, 17171, 17175, 
                                               17176, 17177, 17178, 17179, 17182, 17183, 17184, 17186, 17189, 
                                               17190, 17191, 17192, 17193, 17196, 17197, 17198, 17199, 17200, 
                                               17203, 17204, 17205, 17206, 17207, 17210, 17211, 17212, 17213, 
                                               17214, 17217, 17218, 17219, 17220, 17221, 17224, 17225), class = "Date"), 
                            Total = c(159.819319574035, 100.513902446432, 100.671026272139, 
                                      89.636183769411, 83.6930701040745, 50.3122378901428, 168.724058301167, 
                                      238.800990976061, 174.047961286308, 84.90480213602, 96.6327944162119, 
                                      198.946303771984, 105.202376612078, 75.2787425638002, 104.345665072145, 
                                      79.3962021603985, 96.9288749986742, 109.459300949634, 98.8901916978113, 
                                      116.830828411901, 160.725242652099, 144.215440635792, 165.263571423151, 
                                      74.8805575755291, 81.7886071569258, 118.973870995785, 166.751119591335, 
                                      146.121855191265, 141.303447982398, 339.790780448282, 120.55636917013, 
                                      111.891755247442, 127.68032568788, 100.554207486355, 101.004546687007, 
                                      107.784324411847, 87.4254774508288, 156.928775220726, 118.774701116953
                            )), row.names = c(NA, -39L), class = c("tbl_df", "tbl", "data.frame"
                            ))

因此下一步将所有这些数据从每日数据转换为每周数据。

DATE_MATRIX<-seq.Date(as.Date("2017-01-03"), as.Date("2017-02-28"), by = "day")
Sys.setlocale("LC_TIME", "English")
DATE_MATRIX1<-weekdays(DATE_MATRIX)
library(lubridate)
library(data.table)

DATE_MATRIX_FINAL<-data.frame(Date = DATE_MATRIX, Weekdays = DATE_MATRIX1,week_number=week(DATE_MATRIX),Year= lubridate::year(DATE_MATRIX))
View(DATE_MATRIX_FINAL)

我尝试使用此代码,但不幸的是,此代码从星期二到星期一开始计算星期数。这种计数不好,我想对其进行修复以便从星期一到星期日开始计算星期数,所以任何人都可以帮忙我用这段代码吗? 具有此数据集的P.S数据未合并。我将在此之后进行管理。

1 个答案:

答案 0 :(得分:1)

您可以获取星期数,然后获取每周的let {response: {weather = [], main: {humidity = null, temp_min = null, temp_max = null, feels_like = null, temp = null}}} = res; sum值。

Total

使用aggregate(Total~year_week, transform(Retail_data, year_week = format(Date, "%Y %V")), sum) # year_week Total #1 2017 01 361.0042 #2 2017 02 631.1665 #3 2017 03 554.5319 #4 2017 04 461.1519 #5 2017 05 630.1210 #6 2017 06 607.6577 #7 2017 07 859.6642 #8 2017 08 524.4489 #9 2017 09 275.7035

dplyr