使用日期时间过滤df

时间:2020-01-31 17:35:48

标签: r

我有一个要针对两列(日期和时间)进行过滤的数据框。

我目前有另一个函数(get_datetime),它接受格式为“ YYYYMMDD”的日期和时间为“ HHMM”的日期,并返回POSIXct对象。

如果datetime在一定小时数(hour_diff)之内,则我的过滤条件为on,这是我目前拥有的:

rows <- rows[abs(as.numeric(difftime(datetime, get_datetime(rows$file_date, rows$file_time), units='hours'))) <= hour_diff,]

get_datetime <- function(date, time) {
  #format date and time into POSIXct object
  year <- substr(landfall_date, 1, 4)
  month <- substr(landfall_date, 5, 6)
  day <- substr(landfall_date, 7, 8)
  hour <- substr(landfall_time, 1, nchar(landfall_time) - 2)
  minute <- substr(landfall_time, nchar(landfall_time) - 1, nchar(landfall_time))
  datetime <- as.POSIXct(paste0(year, '-', month, '-', day, ' ', hour, ':', minute, ':00'))
  return(datetime)
}

如何将单个日期和时间(而不是整个日期和时间列)传递给get_datetime,或者我可以通过其他方法正确过滤行吗?

以下是一些示例数据:

enter image description here

structure(list(county = structure(1:6, .Label = c("beaufort", "bertie", "brunswick", "camden", "carteret", "chowan"), class = "factor"), file_date = c(19900724L, 19900724L, 19900725L, 19900725L, 19900726L, 19900726L), file_time = c(300L, 1200L, 1800L, 1800L, 1200L, 1800L)), class = "data.frame", row.names = c(NA, -6L))

datetime <- as.POSIXct('1990-07-25 12:00')
hour_diff <- 12

在上面提供的日期时间和12小时作为hour_diff的情况下,我希望接收中间的4行(伯蒂,布鲁斯维克,卡姆登,卡特莱特)。

1 个答案:

答案 0 :(得分:1)

我建议使用软件包stringranytime来清理日期和时间。

library(anytime)
library(stringr)
library(dplyr)
library(lubridate)

#pad your times that are less than 4 digits
df$file_time = str_pad(df$file_time,width=4,side = "left", pad= "0")

#convert your date and time to datetime 
df$new_dt = anytime(paste(df$file_date, df$file_time))

#create an hour flag
df$hour = hour(df$new_dt)

#filter to get your result:
df %>% filter( hour == '12')
    county file_date file_time              new_dt hour
1   bertie  19900724      1200 1990-07-24 12:00:00   12
2 carteret  19900726      1200 1990-07-26 12:00:00   12

或者如果您希望日期时间范围在1990-07-24 12:00:001990-07-26 12:00:00之间

df %>% filter(new_dt >= '1990-07-24 12:00:00' & new_dt <= '1990-07-26 12:00:00')
     county file_date file_time              new_dt hour
1    bertie  19900724      1200 1990-07-24 12:00:00   12
2 brunswick  19900725      1800 1990-07-25 18:00:00   18
3    camden  19900725      1800 1990-07-25 18:00:00   18
4  carteret  19900726      1200 1990-07-26 12:00:00   12