【问题标题】:R - subset dataframe by Time onlyR - 仅按时间子集数据帧
【发布时间】:2014-11-30 19:35:59
【问题描述】:

我一直在环顾四周,但仍然找不到按时间对数据帧进行子集化的方法,这是示例数据:

 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

结束日期和开始日期采用 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, ])

但这会返回错误。我也试过这个,但效果不佳。

df.time <- subset(df, format('Start Date', '%H:%M') >= '8:00' & format('End Date', '%H:%M') < '9:30'))

如果有人告诉我我做错了什么?谢谢

【问题讨论】:

    标签: r posixct


    【解决方案1】:

    假设开始日期和结束日期始终相同,只有时间不同,并且您希望那些时间从 8:00 或之后开始并在 9:30 之前结束的行,将日期/时间值转换为字符HH:MM 形式的字符串并进行比较:

    subset(DF, format(`Start Date`, "%H:%M") >= "08:00" & 
               format(`End Date`, "%H:%M") < "09:30")
    

    给予:

      Duration            End Date          Start Date
    1      228 2013-01-03 09:10:00 2013-01-03 09:06:00
    

    注意:我们将以下内容用于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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2021-10-10
      相关资源
      最近更新 更多