[英]How to determine if a time is between two other times in R?
Here is my dataframe:这是我的 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
.我想创建一个新列来指示TIME
是否介于sunrise
和sunset
之间。
I thought it would be as simple as an ifelse but that doesnt work and I think it's because of characters...我认为它会像 ifelse 一样简单,但这不起作用,我认为这是因为角色......
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我们使用 POSIXct 转换为日期时间POSIXct
,将其更改为ITime
并进行比较
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
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.