R: set a column of a dataframe as date-time in order to create intervals

前端 未结 1 1975
囚心锁ツ
囚心锁ツ 2021-01-25 05:00

I have a dataframe called data that has date-time information in a column, in the following format: mm/dd/yyyy hh:mm:ss am/pm

What I want is to create put timeperiod val

1条回答
  •  囚心锁ツ
    2021-01-25 05:20

    An option would be

    i1 <- grepl("AM|PM", df1$time)
    out <- as.POSIXct(rep(NA_real_, nrow(df1)), origin = "1970-01-01")
    out[i1] <- as.POSIXct(df1$time[i1], format = "%m/%d/%Y %I:%M:%S %p")
    out[!i1] <- as.POSIXct(df1$time[!i1], format = '%m/%d/%Y %H:%M:%S')
    droplevels(cut(out, breaks = "1 hour"))
    #[1] 2017-05-07 18:00:00 2017-06-08 06:00:00 2017-06-08 08:00:00 2017-06-08 08:00:00 2017-07-07 10:00:00 2017-01-21 08:00:00
    #[7] 2013-01-09 22:00:00 2013-01-09 22:00:00 2013-01-09 22:00:00 2013-01-09 22:00:00
    #Levels: 2013-01-09 22:00:00 2017-01-21 08:00:00 2017-05-07 18:00:00 2017-06-08 06:00:00 2017-06-08 08:00:00 2017-07-07 10:00:00
    

    Or another option is parse_date from parsedate and floor_date

    library(lubridate)
    library(parsedate)
    floor_date(parse_date(df1$time), "hour")
    #[1] "2017-05-07 18:00:00 UTC" "2017-06-08 06:00:00 UTC" "2017-06-08 08:00:00 UTC" "2017-06-08 08:00:00 UTC" "2017-07-07 10:00:00 UTC"
    #[6] "2017-01-21 08:00:00 UTC" "2013-01-09 22:00:00 UTC" "2013-01-09 22:00:00 UTC" "2013-01-09 22:00:00 UTC" "2013-01-09 22:00:00 UTC"
    

    data

    df1 <- structure(list(time = c("05/07/2017 18:00:15", "06/08/2017 06:21:12", 
    "06/08/2017 08:03:11", "06/08/2017 08:12:47", "07/07/2017 10:41:45", 
    "1/21/2017 8:10:20 AM", "1/9/2013 10:01:32 PM", "1/9/2013 10:01:32 PM", 
    "1/9/2013 10:01:32 PM", "1/9/2013 10:01:32 PM"), timeperiod = c(NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA), refer = c(1L, 1L, 1L, 1L, 
    1L, 1L, 2L, 2L, 2L, 2L), x.x = c(23.9737, 23.79394, 23.79394, 
    23.79394, 23.54257, 21.0646, 23.99733, 23.99733, 21.0646, 21.0646
    )), class = "data.frame", row.names = c("1", "2", "3", "4", "5", 
    "6", "7", "8", "9", "10"))
    

    0 讨论(0)
提交回复
热议问题