我有一个如下所示的数据框。
bus_date <- as.Date(c('2017-04-03', '2017-04-04', '2017-04-06', '2017-04-11', '2017-04-13', '2017-04-17'))
sales <- c(100, 110, 120, 200, 300, 100)
daily_sales <- data.frame(bus_date, sales)
是日级别的销售表。
我想创建一个名为“Week_Start”的新变量,它是工作周的日期。我已经实现了各种解决方案,这些解决方案允许我记录周数 (1-52),但我需要实际的周开始日期。
如果(bus_date 是星期一) 返回(bus_date) 别的 返回(bus_date 之前的星期一)
所以我得到的数据框看起来像:
Week_Start <- as.Date(c('2017-04-03', '2017-04-03', '2017-04-03', '2017-04-10', '2017-04-10', '2017-04-17'))
daily_sales2 <- data.frame(bus_date, sales, Week_Start)
我知道可能有一种简单的方法可以做到这一点,但不确定从哪里开始。谢谢。
最佳答案
来自 ?strptime
%w Weekday as decimal number (0–6, Sunday is 0).
%W Week of the year as decimal number (00–53) using Monday as the first day of week (and typically with the first Monday of the year as day 1 of week 1). The UK convention.
as.Date(format(daily_sales$bus_date, "%Y-%W-1"), format = "%Y-%W-%w")
#[1] "2017-04-03" "2017-04-03" "2017-04-03" "2017-04-10" "2017-04-10" "2017-04-17"
关于r - 在 R 中创建 "Week_Start"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43480629/