关于r:使用datetime过滤df


Filter df with datetime

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

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

如果日期时间在一定小时数内(hour_diff),我的过滤条件将打开,而这就是我目前所拥有的:

1
2
3
4
5
6
7
8
9
10
11
12
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

1
2
3
4
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行(伯蒂,布鲁斯维克,卡姆登,卡特莱特)。


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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')
1
2
3
    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

之间

1
df %>% filter(new_dt >= '1990-07-24 12:00:00' & new_dt <= '1990-07-26 12:00:00')
1
2
3
4
5
     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