r - 在 R 中创建 "Week_Start"变量

标签 r date

我有一个如下所示的数据框。

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/

相关文章:

php - 在 2 个不同格式的日期之间搜索

javascript - 如何在自定义JQuery中添加日期原始/后缀?

r - 在 dplyr 中汇总并为没有值的类别插入 0

带有 R 的列表的所有对象中的 rowSums

r - 如何改变 R 点阵条形图中非分组因素的颜色?

R install.packages 返回 "failed to create lock directory"

string - 识别字符向量中具有重复字母的项目

php - 从日期减去一定数量的小时、天、月或年

php - 数学运算 PHP 与时间

date - golang 中的 ISOWeek() 没有返回一年中一周的期望值