Home > database >  select dates between ranges in r
select dates between ranges in r

Time:01-18

In dataset, I have date variable that has this format : "2020-01-01" This variable is stored as "Date" format

This code works:

dataset[which(dataset$date_variable > 2020-01-01),]

This code also works:

 dataset[which(dataset$date_variable > 2020-01-19),]

But together I get no output:

dataset[which(dataset$date_variable > 2020-01-01 & dataset$date_variable < 2020-01-19),]
# produce empty result

How I can correct this code? How in R to subset between date range? I should maybe convert variable type format?

CodePudding user response:

2018-01-25 means 2018 minus 1 minus 25. Surround the dates with quotes since Date objects can be compared to character representations. Using the reproducible input in the Note at the end we have the following.

x[x > "2018-01-24" & x < "2018-01-26"]
## [1] "2018-01-25"

Note

x <- structure(c(17556, 17555, 17554), class = "Date")
x
## [1] "2018-01-25" "2018-01-24" "2018-01-23"
  • Related