vladli
vladli

Reputation: 1573

Working with sequences of dates in R

I have a data.frame with a column of dates in POSIXct. What I'm trying to do is to create a new logical column that will show if the dates are in some range. For example, if I have this vector: "2016-10-16 GMT" "2016-04-30 GMT" "2016-08-04 GMT" "2016-11-07 GMT" "2016-09-06 GMT" "2016-01-11 GMT" and have a range

date_from <- "2016-10-10"
date_to <- "2016-11-20"

the new column should be

TRUE, FALSE, FALSE, TRUE, FALSE, FALSE

How do I achieve this behavior? The real dataset is tens of thousands rows long and the only easy way to do this for me would be to cycle through all rows, which is not a good way of doing it i believe.

Upvotes: 0

Views: 67

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47340

With only base R you can do this:

as.Date(x) %in% as.Date(date_from):as.Date(date_to)
# [1]  TRUE FALSE FALSE  TRUE FALSE FALSE

data

x <- c("2016-10-16 GMT","2016-04-30 GMT","2016-08-04 GMT","2016-11-07 GMT","2016-09-06 GMT","2016-01-11 GMT") 
date_from <- "2016-10-10"
date_to <- "2016-11-20"

Upvotes: 2

MLEN
MLEN

Reputation: 2561

Using data.table so you wont need to use <> and lubridate functions to easily convert the dates.

library(data.table)
library(lubridate)

f <- c("2016-10-16 GMT", 
"2016-04-30 GMT", 
"2016-08-04 GMT", 
"2016-11-07 GMT", 
"2016-09-06 GMT", 
"2016-01-11 GMT")

f <- ymd(f)

date_from <- ymd("2016-10-10")
date_to <- ymd("2016-11-20")

f %between% c(date_from, date_to) # From data.table
f %within% interval(date_from, date_to) # From lubridate

Upvotes: 1

Related Questions