cut()
从基础R具有用于假定周的星期一开始默认(但可使用start.on.monday = FALSE
被改变为星期日)Date
类和POSIXt
的对象的两种方法。
dates <- c("2016-04-04", "2016-04-05", "2016-04-06", "2016-04-07", "2016-04-08",
"2016-04-09", "2016-04-10", "2016-04-11", "2016-04-12", "2016-04-13",
"2016-04-14")
result <- data.frame(
dates,
cut_Date = cut(as.Date(dates), "week"),
cut_POSIXt = cut(as.POSIXct(dates), "week"),
stringsAsFactors = FALSE)
result
# dates cut_Date cut_POSIXt
#1 2016-04-04 2016-04-04 2016-04-04
#2 2016-04-05 2016-04-04 2016-04-04
#3 2016-04-06 2016-04-04 2016-04-04
#4 2016-04-07 2016-04-04 2016-04-04
#5 2016-04-08 2016-04-04 2016-04-04
#6 2016-04-09 2016-04-04 2016-04-04
#7 2016-04-10 2016-04-04 2016-04-04
#8 2016-04-11 2016-04-11 2016-04-11
#9 2016-04-12 2016-04-11 2016-04-11
#10 2016-04-13 2016-04-11 2016-04-11
#11 2016-04-14 2016-04-11 2016-04-11
注意cut()
收益因素是完美的聚集由OP的要求:
str(result)
#'data.frame': 11 obs. of 3 variables:
# $ dates : chr "2016-04-04" "2016-04-05" "2016-04-06" "2016-04-07" ...
# $ cut_Date : Factor w/ 2 levels "2016-04-04","2016-04-11": 1 1 1 1 1 1 1 2 2 2 ...
# $ cut_POSIXt: Factor w/ 2 levels "2016-04-04","2016-04-11": 1 1 1 1 1 1 1 2 2 2 ...
然而,绘制累计值与ggplot2
(如果有大量的星期可能使轴线杂波),从离散时间刻度切换到连续时间刻度可能会更好。然后,有必要强制因素回Date
或POSIXct
:
as.Date(as.character(result$cut_Date))
as.POSIXct(as.character(result$cut_Date))
来源
2017-05-06 08:17:33
Uwe
的可能重复[R:如何判断在同一个星期日期(http://stackoverflow.com/questions/43775261/r-如何判断在同一周的日期) – Uwe
似乎[this](http://stackoverflow.com/questions/26160117/changing-lubridate-function-to-start-on-monday-rather星期日)可能会有所帮助。 –
你可以从你的日期中减去'wday'。 'lubridate'和'data.table'具有这个函数的实现。 – MichaelChirico