Compare different dates with each other

Hey there,

I want to compare dates with each other:
"Alltimes" contains 3 dates (%y%m%d_%h%m%s).
For each date, I want to find out, if it is in range of the dates given in "times_sel".
F.e. is 20200101_195240 in range of 20200101_195137 -> 20200102_053623, is 20200101_195240 in range of 20200114_172615 -> 20200114_200423 and so on.
If it lies in range of times_sel[1] OR times_sel[2] OR times_sel[3], i want to save it in a new vector.


alltimes <- data.frame(
  stringsAsFactors = FALSE,
                V1 = c("20200101_195240", "20200105_044527", "20200116_225426")
)


times_sel <- data.frame(
  stringsAsFactors = FALSE,
             Start = c("20200101_195137", "20200114_172615", "20200116_172905"),
               End = c("20200102_053623", "20200114_200423", "20200116_230726")
)

So far I tried:

final_sel <- vector(mode = "numeric")

for (i in 1:NROW(alltimes)) {
  for (j in 1:NROW(times_sel)) {
    runif((alltimes[i] >= as.numeric(times_sel$Start[j]) && alltimes[i] <= as.numeric(times_sel$End[j])), final_sel <- c(final_sel, alltimes[i]), next)
  }
}

I have little experience in R-programming, so I hope to find some help here.

Hi!

To help us help you, could you please turn this into a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

error: error in [.data.frame (alltimes, i) : undefined columns selected

warning: NA created

Is this what you mean?

library(tidyverse)
library(lubridate)

alltimes <- data.frame(
    stringsAsFactors = FALSE,
    V1 = c("20200101_195240", "20200105_044527", "20200116_225426")
)


times_sel <- data.frame(
    stringsAsFactors = FALSE,
    Start = c("20200101_195137", "20200114_172615", "20200116_172905"),
    End = c("20200102_053623", "20200114_200423", "20200116_230726")
)

alltimes %>% 
    mutate(V1 = ymd_hms(V1)) %>% 
    rowwise() %>% 
    mutate(flag = any(map2_lgl(ymd_hms(times_sel$Start),
                               ymd_hms(times_sel$End),
                               ~ V1 >= .x & V1 <= .y))) %>% 
    filter(flag) %>% 
    select(V1)
#> # A tibble: 2 x 1
#> # Rowwise: 
#>   V1                 
#>   <dttm>             
#> 1 2020-01-01 19:52:40
#> 2 2020-01-16 22:54:26

Created on 2021-07-18 by the reprex package (v2.0.0)

1 Like

Hey,

yes, this solves my problem.

Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.