Convert date to Monday of that week

I found this formula for converting dates on Monday of that week:

x <- as.Date("2015-07-17")
y <- (x-c(6:0))[format((x-c(6:0)),"%w")=="1"]

      

How can I adapt the formula for use on a date column?


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"]

      

Throws:

Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L,  : 
  invalid 'trim' argument

      

+3


source to share


2 answers


You can use this function:

prevM <-function(x)
        7 * floor(as.numeric(x-1+4) / 7) + as.Date(1-4,origin = "1970-01-01")

      

Then

 prevM(as.Date(c("2015-07-17","2015-07-16","1974-02-10")))

      



Will produce:

[1] "2015-07-13" "2015-07-13" "1974-02-04"

      

You can find it here: Previous Monday Date

+6


source


try it



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"]
}

      

0


source







All Articles