我有一个数据框架,第一列是"date"格式为YYYY-MM-DD HH:MM:SS
.
我想要能够删除数据帧中所有的行之前的某个日期和时间?
因此,例如,如果下面我想删除所有行在20121-07-19 11:30:30之前。我该怎么做呢?
我想要过滤的时间也作为变量"startdatetime"保存到环境中
date
2021-07-19 11:30:00
2021-07-19 11:30:15
2021-07-19 11:30:30
2021-07-19 11:30:45
2021-07-19 11:31:00
你可以使用
library(dplyr)
df %>%
# filter(date >= as.POSIXct("2021-07-19 11:30:30"))
filter(date >= "2021-07-19 11:30:30") # thanks to ThomasIsCoding: as.POSIXct isn't necessary
返回
date
1 2021-07-19 11:30:30
2 2021-07-19 11:30:45
3 2021-07-19 11:31:00
我将lubridate
和dplyr
一起使用。lubridate
被设计为具有日期和时间的操作。
复制你的例子:
library(lubridate)
library(dplyr)
dates <- c("2021-07-19 11:30:00","2021-07-19 11:30:15","2021-07-19 11:30:30",
"2021-07-19 11:30:45","2021-07-19 11:31:00")
#coerce string to Date and Time
dates <- ymd_hms(dates) #which means year, month, day, hour, minute and second
df <- data.frame(date = dates)
df %>% filter(date >= ymd_hms("2021-07-19 11:30:30"))