Skip to content

Instantly share code, notes, and snippets.

@aammd
Created October 10, 2014 18:57
Show Gist options
  • Save aammd/12d7b27dddf49b16ecc3 to your computer and use it in GitHub Desktop.
Save aammd/12d7b27dddf49b16ecc3 to your computer and use it in GitHub Desktop.
Comparing a list of dates to a list of intervals
library(dplyr)
library(lubridate)
## when will the two friends be in the same town?
visits <- data.frame(am_in_town = c(
ymd(20140501) %--% ymd(20140520),
ymd(20140615) %--% ymd(20140620),
ymd(20140701) %--% ymd(20140710),
ymd(20141101) %--% ymd(20141112)
)
)
## Karaoke happens on every thursday
karaoke <- data.frame(karaoketime = ymd(20140109) + ddays(seq(from = 7, to = 350, by = 7)))
## how many opportunities will they have to karaoke?
## won't work
karaoke %>%
rowwise %>%
mutate(karaoke_nite = any(karaoketime %within% visits[["am_in_town"]]))
is_in_an_interval <- function(a_date, ints = visits[["am_in_town"]]){
any(a_date %within% ints)
}
is_in_an_interval(karaoke$karaoketime[[1]])
sapply(karaoke$karaoketime, is_in_an_interval)
## also won't work
karaoke %>%
rowwise %>%
mutate(karaoke_nite = is_in_an_interval(karaoketime))
## works fine
karaoke %>%
rowwise %>%
do(karaoke_nite = is_in_an_interval(.$karaoketime)) %>%
ungroup
library(microbenchmark)
microbenchmark({karaoke %>%
rowwise %>%
do(karaoke_nite = is_in_an_interval(.$karaoketime)) %>%
ungroup},
sapply(karaoke$karaoketime, is_in_an_interval))
## perhaps the simplest answer is to rely on sapply
karaoke %>%
mutate(karaokenite = sapply(karaoketime, is_in_an_interval))
@karawoo
Copy link

karawoo commented Oct 10, 2014

This is what I did to subset straight away instead of creating a true/false column:

karaoke %>% 
  filter(sapply(karaoketime, is_in_an_interval))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment