Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting data.table set by date range in R

I have a large dataset in data.table that I'd like to subset by a date range. My data set looks like this:

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)) 

I'd like to be able to choose a date range directly from the as.Date column without using the yr, mo, or da columns. Currently, I'm subsetting by mo and it's extremely clunky at times, especially when years switch over. A more elegant method of doing this would make my life infinitely easier.

Thanks in advance!

like image 580
black_sheep07 Avatar asked Mar 15 '14 06:03

black_sheep07


People also ask

How do I sort a table by date in R?

Here order() function is used to sort the dataframe by R using order() function based on the date column, we have to convert the date column to date with the format, this will sort in ascending order.


2 Answers

Why not:

testset[date>="2013-08-02" & date<="2013-11-01"] 
like image 120
Troy Avatar answered Sep 17 '22 18:09

Troy


See also:

?`%between%` 

Works like this:

testset[date %between% c("2013-08-02", "2013-11-01")] 
like image 27
Daniel Krizian Avatar answered Sep 21 '22 18:09

Daniel Krizian