我一直在寻找,但我仍然找不到按时间对数据帧进行子集化的方法,这里是示例数据:
Duration End Date Start Date
228 2013-01-03 09:10:00 2013-01-03 09:06:00
1675 2013-01-04 17:34:00 2013-01-04 17:06:00
393 2013-01-04 17:54:00 2013-01-04 17:48:00
426 2013-01-04 11:10:00 2013-01-04 11:03:00
827 2013-01-01 16:13:00 2013-01-01 15:59:00
780 2013-01-01 16:13:00 2013-01-01 16:00:00
Run Code Online (Sandbox Code Playgroud)
结束日期和开始日期是POSIXct格式,如果我只在8:00到9:30之间的时间,这是我尝试过的.
tm1 <- as.POSIXct("08:00", format = "%H:%M")
tm2 <- as.POSIXct("09:30", format = "%H:%M")
df.time <- with(df, df[format('Start Date', '%H:%M')>= tm1 & format('End Date', '%H:%M')< tm2, ])
Run Code Online (Sandbox Code Playgroud)
但这会返回错误.我也试过这个,但它没有用.
df.time <- subset(df, format('Start Date', '%H:%M') >= '8:00' & format('End Date', '%H:%M') < '9:30'))
Run Code Online (Sandbox Code Playgroud)
如果有人告诉我我做错了什么?谢谢
假设开始日期和结束日期始终相同且只有时间不同,并且您希望那些时间从8:00开始或在8:00之后开始并在9:30之前结束的行,请将日期/时间值转换为字符串的字符串.形式HH:MM并比较:
subset(DF, format(`Start Date`, "%H:%M") >= "08:00" &
format(`End Date`, "%H:%M") < "09:30")
Run Code Online (Sandbox Code Playgroud)
赠送:
Duration End Date Start Date
1 228 2013-01-03 09:10:00 2013-01-03 09:06:00
Run Code Online (Sandbox Code Playgroud)
注意:我们使用以下内容DF.(下次请用于dput以可重复的形式提供您的数据.)
DF <- structure(list(Duration = c(228L, 1675L, 393L, 426L, 827L, 780L
), `End Date` = structure(c(1357222200, 1357338840, 1357340040,
1357315800, 1357074780, 1357074780), class = c("POSIXct", "POSIXt"
), tzone = ""), `Start Date` = structure(c(1357221960, 1357337160,
1357339680, 1357315380, 1357073940, 1357074000), class = c("POSIXct",
"POSIXt"), tzone = "")), .Names = c("Duration", "End Date", "Start Date"
), row.names = c(NA, -6L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)