简体   繁体   English

周编号到R中每个星期的开始日期

[英]Week Number to Starting Date of Each Week in R

A few questions have come close to what I am looking for, but I can't find one that gets it right on. 一些问题已经接近我要寻找的问题,但是我找不到一个可以正确解决的问题。

I have sales data for several products for each day over a 6-year period. 在六年的时间内,我每天都有几种产品的销售数据。 I summed the data by week, starting January 1, 2008. During the period 1/1/08-12/30/13, there were 313 weeks, so I just created dataframes for each product that contained columns for week numbers 1-313 and the weekly sales for each respective week. 我从2008年1月1日开始按周对数据进行汇总。在1/1 / 08-12 / 30/13期间,共有313周,因此我为每个产品创建了数据框,其中包含第1-313周的列以及每个星期的每周销售额。

I am plotting them with ggplot2, adding trendlines, etc. 我正在用ggplot2绘制它们,添加趋势线等。

The x-axis obviously uses the week number for its values, but I would prefer if it used the actual dates of the start of each week (Jaunary 1, 2008, a Tuesday, January 8, 2008, December 25, 2013, etc). x轴显然使用周数作为其值,但是如果它使用每个星期开始的实际日期(2008年1月1日,星期二,2008年1月8日,2013年12月25日,等等),我会更愿意。 。

What is the best way to do this? 做这个的最好方式是什么? How can I convert weeks 1-313 into their respective Start of Week dates? 如何将1-313周转换为各自的“周开始”日期? Or, is there a way to override the axis values on the plot itself? 或者,是否有一种方法可以覆盖图本身上的轴值?

To convert your week numbers to dates try something like this 要将周数转换为日期,请尝试如下操作

weeks <- 1:313
start.date <- as.Date("2007/12/31")
y <- start.date + (weeks - 1)*7

head(y)
"2007-12-31" "2008-01-07" "2008-01-14" "2008-01-21" "2008-01-28" "2008-02-04"

Use package:lubridate ? 使用package:lubridate吗?

Sample data (which you should have provided): 样本数据(您应该提供):

> df = data.frame(wid=1:10,z=runif(10))
> head(df)
  wid         z
1   1 0.2071595
2   2 0.4313403
3   3 0.7063967
4   4 0.2245014
5   5 0.2004542
6   6 0.1231366

Assuming your data are consecutive, with no gaps: 假设您的数据是连续的,没有间隙:

> require(lubridate)
> df$week=mdy("Jan 1 2008") + weeks(0:(nrow(df)-1))
> head(df)
  wid         z       week
1   1 0.2071595 2008-01-01
2   2 0.4313403 2008-01-08
3   3 0.7063967 2008-01-15
4   4 0.2245014 2008-01-22
5   5 0.2004542 2008-01-29
6   6 0.1231366 2008-02-05

Then plot for nice labels: 然后绘制漂亮的标签:

> require(ggplot2)
> ggplot(df,aes(x=week,y=z))+geom_line()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM