Subset rows according to a range of time

后端 未结 4 1120
无人及你
无人及你 2020-12-03 05:31

I have a data frame that looks like that

            date_time loc_id node  energy   kgco2 
1 2009-02-27 00:11:08     87  103 0.00000 0.00000 
2 2009-02-27 0         


        
相关标签:
4条回答
  • 2020-12-03 05:46

    One way to do it is to use lubridate and define an interval :

    library(lubridate)
    
    date1 <- as.POSIXct("2009-02-27 02:00:00")
    date2 <- as.POSIXct("2009-02-27 05:00:00")
    int <- new_interval(date1, date2)
    
    df[df$datetime %within% int,]
    
    0 讨论(0)
  • 2020-12-03 05:53
    • Use the lubridate::hours function to extract the hour number.
    • Then use dplyr::filter function to get the result.
    0 讨论(0)
  • 2020-12-03 06:02

    I would suggest using xts package for time series analysis. It has very convenient subsetting functions.

    DF
    ##             date_time loc_id node  energy   kgco2
    ## 1 2009-02-27 00:11:08     87  103 0.00000 0.00000
    ## 2 2009-02-27 01:05:05     87  103 7.00000 3.75900
    ## 3 2009-02-27 02:05:05     87  103 6.40039 3.43701
    ## 4 2009-02-27 03:05:05     87  103 4.79883 2.57697
    ## 5 2009-02-27 04:05:05     87  103 4.10156 2.20254
    ## 6 2009-02-27 05:05:05     87  103 2.59961 1.39599
    
    require(xts)
    XTSDATA <- xts(DF[, -1], DF[, 1])
    XTSDATA["T02:00:00/T05:00:00"]
    ##                     loc_id node  energy   kgco2
    ## 2009-02-27 02:05:05     87  103 6.40039 3.43701
    ## 2009-02-27 03:05:05     87  103 4.79883 2.57697
    ## 2009-02-27 04:05:05     87  103 4.10156 2.20254
    
    0 讨论(0)
  • 2020-12-03 06:13

    I'd use the lubridate package and the hour() function to make your life easier...

    require( lubridate )
    
    with( df , df[ hour( date_time ) >= 2 & hour( date_time ) < 5 , ] )
    
    #            date_time loc_id node  energy   kgco2
    #3 2009-02-27 02:05:05     87  103 6.40039 3.43701
    #4 2009-02-27 03:05:05     87  103 4.79883 2.57697
    #5 2009-02-27 04:05:05     87  103 4.10156 2.20254
    
    0 讨论(0)
提交回复
热议问题