我有一个数据集,该数据集的订购日期为2017年1月7日至2018年6月30日。 我想提取星期数。我要为01/07到07/07对应的天分配星期数01。我使用了lubridate软件包,但它以01/01为起点。是否可以设置偏移值? 我的代码:
order$start_week_date <- floor_date(as.Date(order$order_date),
unit="week" , week_start = getOption("lubridate.week.start", 1))
order$week_no <- strftime( order$start_week_date ,format="%V")
答案 0 :(得分:3)
您如何看待这种方法?
customweek <- function(dateweek, dateorigin){
return(as.integer(round((ymd(dateweek)-ymd(dateorigin) + 1)/7,0)))
}
数据周将是您的起始日期和日期(均为YYYY / MM / DD格式)。 因此:
customweek("20170107", "20170101")
产生1作为结果。
答案 1 :(得分:2)
我可能会使用类似以下的函数,该函数使用R的整数除法运算符%/%
,根据发源后的天数计算周数:
library(lubridate)
f <- function(date, origin) {
(as.numeric(dmy(date) - dmy(origin)) %/% 7) + 1
}
## Try it out
dd <- c("01/07/2017", "07/07/2017", "08/07/2017", "30/06/2018")
f(dd, origin = "01/07/2017")
## [1] 1 1 2 53
答案 2 :(得分:0)
您可以将数据转换为xts
对象,并使用index
属性的功能。
# mock-up data
data <- data.frame(dates=seq(from = as.Date("2017-07-01"), to = as.Date("2018-06-30"), by = "days"), data = rnorm(length(dates)))
# load libraries
library(xts) # a powerful library that makes work with time series pretty easy
library(dplyr)
# create an xts object (an xts object is formed by the matrix of observations, ordered by an index of dates)
df_xts <- xts(data[,-1], order.by = data$dates)
data <- data %>%
# use ".indexweek" to return the week number since beginning of 1970
mutate(week_nr = .indexweek(df_xts)) %>%
# assign week number starting from 1
mutate(week_nr = week_nr - min(week_nr) + 1) %>%
# maybe add 0 in front of weeks 1-9
mutate(week_nr = ifelse(week_nr < 10, paste0("0", week_nr), week_nr))
输出:
> head(data)
dates data week_nr
1 2017-07-01 -0.99142495 01
2 2017-07-02 0.19130095 01
3 2017-07-03 -0.03775566 02
4 2017-07-04 1.24858796 02
5 2017-07-05 0.59453045 02
6 2017-07-06 -0.18317437 02