0

I would like to subset my dataset based on a range. My date column is of type 'Date' and looks like this (monthly):

 Date
1926-07-31
1926-10-31
1927-01-31
1927-04-30

From other forum posts (such as this one: Subsetting data.table set by date range in R) I have gathered a few approaches, none of which worked however:

df1 <- subset(df, Date > 1927-07-31 & Date < 1927-10-31)
df1<-df[df$Date>="1927-07-31" & df$Date<="1927-10-31"]

Is there a simple way of doing this (possibly without a new package)?

Niccola Tartaglia
  • 1,537
  • 2
  • 26
  • 40

1 Answers1

3

What you post should work

c(as.Date("2018-01-01"), as.Date("2017-01-01")) > "2017-01-01"
#R> [1]  TRUE FALSE

You do likely want to have a sharp inequality in of the two inequalities you write.

What may be the cause of your error is the way that you are susbetting in the latter example. E.g., see

> df <- data.frame(a = 1:5, b = letters[1:5])
> df[1:2]
#R>   a b
#R> 1 1 a
#R> 2 2 b
#R> 3 3 c
#R> 4 4 d
#R> 5 5 e
> df[1:2, ]
#R>   a b
#R> 1 1 a
#R> 2 2 b
  • 3
    As an extra reference for the asker, being able to compare character and Date objects is covered in the help files - `?Ops.Date` - you can do a valid comparison between: "*date objects or character vectors. (Character vectors are converted by as.Date.)*". – thelatemail Feb 26 '18 at 23:29
  • Good reference. This also highlight why `Date > 1927-07-31 & Date < 1927-10-31` is not working. There is no character quotes which I just noticed. Thus, e.g., `as.Date("1970-01-01") + 2001 > 2002-01-01` is `TRUE` while `as.Date("1970-01-01") + 2000 > 2002-01-01` is `FALSE` since `1970-01-01` is the default origin. – Benjamin Christoffersen Feb 26 '18 at 23:36
  • You are right, what I posted did work, the interval I chose was too small so that no dates satisfied the condition, leaving me with an empty dataframe. Embarrassing oversight on my part, I blame that lack of coffee. Thank you for the explanation, and thanks also for the top with Ops.Date. I will check it out. – Niccola Tartaglia Feb 27 '18 at 07:41