firmo23
firmo23

Reputation: 8404

Subset a dataframe with dynamic dates by date range in R

I have the dataframe below:

dates <- data.frame(rep(
  seq(as.Date('2017-01-01'), as.Date('2017-12-31'), by = 'days'), 
  times = 1))
colnames(dates)<-"day"

And I would like to subset it by the last 2 weeks. The thing is that I do not want to use something like:

dates[day>="2017-18-02" & day<="2017-05-02"]

because the dataframe will be updated over time and the last date will be changing.

Upvotes: 0

Views: 297

Answers (3)

akrun
akrun

Reputation: 887118

We can extract the week and create a logical vector

testset[testset[, {i1 <- as.numeric(format(date, "%W")); .I[i1 == max(i1)]}]]

If it is more than one week

testset[testset[, {i1 <- as.numeric(format(date, "%W"))
                   .I[i1 %in% tail(unique(sort(i1)), 2)] }]]

Upvotes: 0

Vishal Katti
Vishal Katti

Reputation: 652

You could create a Week column from the date and filter for max(Week)

    library(data.table)
    #> Warning: package 'data.table' was built under R version 3.6.2

    testset <- data.table(date=as.Date(c("2013-07-02","2013-08-03","2013-09-04",
                                     "2013-10-05","2013-11-06")), 
                      yr = c(2013,2013,2013,2013,2013), 
                      mo = c(07,08,09,10,11),
                      da = c(02,03,04,05,06), 
                      plant = LETTERS[1:5], 
                      product = as.factor(letters[26:22]), 
                      rating = runif(25))

    testset$Week <- format(testset$date, "%W")

    testset[Week == max(Week)]
    #>          date   yr mo da plant product    rating Week
    #> 1: 2013-11-06 2013 11  6     E       v 0.7794414   44
    #> 2: 2013-11-06 2013 11  6     E       v 0.4971975   44
    #> 3: 2013-11-06 2013 11  6     E       v 0.6272580   44
    #> 4: 2013-11-06 2013 11  6     E       v 0.3748460   44
    #> 5: 2013-11-06 2013 11  6     E       v 0.6683196   44

Upvotes: 0

trevin_flick
trevin_flick

Reputation: 328

A possible solution with lubridate and dplyr

library(lubridate)
library(dplyr)

testset %>%
filter(week(testset$date) == max(week(testset$date)))

Upvotes: 1

Related Questions