我找到了将日期转换为那个星期的星期一的公式:
x <- as.Date("2015-07-17")
y <- (x-c(6:0))[format((x-c(6:0)),"%w")=="1"]
如何调整公式以用于日期列?
df <- data.frame(date = c("2014-08-09", "2014-08-10", "2014-08-11", "2014-11-04"))
df$date <- as.Date(df$date)
df$week <- (df$date-c(6:0))[format((df$date-c(6:0)),"%w")=="1"]
将抛出:
Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, :
invalid 'trim' argument
你可以使用这个函数:
prevM <-function(x)
7 * floor(as.numeric(x-1+4) / 7) + as.Date(1-4,origin = "1970-01-01")
然后 prevM(as.Date(c("2015-07-17","2015-07-16","1974-02-10")))
会产生:
[1] "2015-07-13" "2015-07-13" "1974-02-04"
你可以在这里找到:上星期一日期
试试这个
df <- data.frame(date = c("2014-08-09", "2014-08-10", "2014-08-11", "2014-11-04"))
df$date <- as.Date(df$date)
for(i in 1:dim(df)[1]){
df$date[i] <- (as.Date(df$date[i])-c(6:0))[format((as.Date(df$date[i])-c(6:0)),"%w")=="1"]
}