简体   繁体   中英

How to determine if a time is between two other times in R?

Here is my dataframe:

  TIME      data   sunrise     sunset     
  <chr>     <chr>  <chr>       <chr>      
1 6:00 AM   ddd    07:19:53 AM 04:41:13 PM
2 1:15 PM   fff    07:19:53 AM 04:41:13 PM
3 01:00 AM  rrrr   07:19:52 AM 04:42:08 PM
4 10:28 AM  btv    07:19:52 AM 04:42:08 PM
5 11:45 AM  gored  07:19:52 AM 04:42:08 PM

And I want to make a new column to indicate if TIME falls between sunrise and sunset .

I thought it would be as simple as an ifelse but that doesnt work and I think it's because of characters...

df  %>% 
  mutate(daylight = ifelse(between(TIME, sunrise,sunset) == TRUE,1,0))

It should look like this:

  TIME      data   sunrise     sunset       daylight
  <chr>     <chr>  <chr>       <chr>      
1 6:00 AM   ddd    07:19:53 AM 04:41:13 PM  0
2 1:15 PM   fff    07:19:53 AM 04:41:13 PM  1
3 01:00 AM  rrrr   07:19:52 AM 04:42:08 PM  0
4 10:28 AM  btv    07:19:52 AM 04:42:08 PM  1
5 11:45 AM  gored  07:19:52 AM 04:42:08 PM  1

DATA

df <- structure(list(TIME = c("6:00 AM", "1:15 PM", "1:00 AM", "10:28 AM", 
"11:45 AM"), sunrise = c("07:19:53 AM", "07:19:53 AM", "07:19:52 AM", 
"07:19:52 AM", "07:19:52 AM"), sunset = c("04:41:13 PM", "04:41:13 PM", 
"04:42:08 PM", "04:42:08 PM", "04:42:08 PM")), row.names = c(NA, 
-5L), groups = structure(list(.rows = structure(list(1L, 2L, 
    3L, 4L, 5L), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame")), class = c("rowwise_df", "tbl_df", "tbl", 
"data.frame"))

We convert to datetime class with POSIXct , change that to ITime and do the comparison

library(dplyr)
library(data.table)
df %>%
   mutate(TIME = as.ITime(as.POSIXct(TIME, format = '%I:%M %p')), 
          sunrise = as.ITime(as.POSIXct(sunrise, format = '%I:%M:%S %p')), 
          sunset = as.POSIXct(sunset, format = '%I:%M:%S %p'), 
          daylight = as.integer(TIME >= sunrise & TIME <= sunset))
#      TIME  data  sunrise              sunset daylight
#1 06:00:00   ddd 07:19:53 2020-07-13 16:41:13        0
#2 13:15:00   fff 07:19:53 2020-07-13 16:41:13        1
#3 01:00:00  rrrr 07:19:52 2020-07-13 16:42:08        0
#4 10:28:00   btv 07:19:52 2020-07-13 16:42:08        1
#5 11:45:00 gored 07:19:52 2020-07-13 16:42:08        1

data

df <- structure(list(TIME = c("6:00 AM", "1:15 PM", "01:00 AM", "10:28 AM", 
"11:45 AM"), data = c("ddd", "fff", "rrrr", "btv", "gored"), 
    sunrise = c("07:19:53 AM", "07:19:53 AM", "07:19:52 AM", 
    "07:19:52 AM", "07:19:52 AM"), sunset = c("04:41:13 PM", 
    "04:41:13 PM", "04:42:08 PM", "04:42:08 PM", "04:42:08 PM"
    )), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM