【问题标题】:Calculate Avg Time in R计算 R 中的平均时间
【发布时间】:2016-08-24 12:13:54
【问题描述】:

我的Dataframecopy1

    copy1
Source: local data frame [4 x 4]
Groups: GM [2]

      GM Avg.Start.Time Avg.Close.Time Avg.Last.Task.Duration
  (fctr)         (fctr)         (fctr)                  (int)
1   ED          13:15          16:16                    181
2   ED          16:12          17:44                     92
3   LD          15:32          17:27                    115
4   LD          14:38          17:11                    153

我要计算Avg.Close.TimeGM

我试过了:

copy1$Avg.Start.Time <-strptime(copy1$Avg.Start.Time, "%H:%M")
copy1%>%group_by(GM)%>%
        summarise(mean(copy1$Avg.Start.Time,na.rm=T))

但是得到这个:

Error: column 'Avg.Start.Time' has unsupported type : POSIXlt, POSIXt

我也尝试过使用lubridate:

copy1$Avg.Start.Time <- hm(copy1$Avg.Start.Time)

mean(copy1$Avg.Start.Time,na.rm = T)

但是得到“0”

任何想法如何计算Avg.Start.Time Per GM

【问题讨论】:

    标签: r time hour minute


    【解决方案1】:

    您可以使用as.POSIXct进行转换,其结果可用于mean

    result <- copy1%>%group_by(GM)%>%
      summarise(mean(as.POSIXct(Avg.Start.Time, format="%M:%S"),na.rm=T))
    

    但是,这会将当前日期添加到时间:

    print(result)
    ## A tibble: 2 x 2
    ##      GM mean(as.POSIXct(copy1$Avg.Start.Time,...
    ##  <fctr>                                   <time>
    ##1     ED                      2016-08-24 00:14:54
    ##2     LD                      2016-08-24 00:15:05
    

    正如OP所指出的,我们可以format结果删除日期:

    result <- copy1%>%group_by(GM)%>%
      summarise(Avg.Start.Time=format(mean(as.POSIXct(Avg.Start.Time, format="%M:%S"),na.rm=T), format="%M:%S"))
    ## A tibble: 2 x 2
    ##      GM Avg.Start.Time
    ##  <fctr>          <chr>
    ##1     ED          14:43
    ##2     LD          15:05
    

    【讨论】:

    • 谢谢它不是一个有效的答案。两次返回相同
    • @Shery:抱歉,只是在summarise 中使用了copy1$Avg.Start.Time 而不是Avg.Start.Time。无论如何,另一个答案要好得多,因为它去掉了日期。
    • 您也可以在末尾使用format(format = "%H:%M") 格式化时间
    【解决方案2】:

    您需要先将列转换为时间格式,

    copy1$Avg.Start.Time <- as.POSIXct(copy1$Avg.Start.Time, format = "%H:%M")
    

    然后,您可以使用基础 R 中的 aggregate 为每个 GM 获取 mean

    aggregate(Avg.Start.Time~GM, copy1, mean)
    
    #  GM      Avg.Start.Time
    #1 ED 2016-08-24 14:43:30
    #2 LD 2016-08-24 15:05:00
    

    如果你想要 HH:MM 格式,你可以将它包裹在 format

    aggregate(Avg.Start.Time~GM, copy1, function(x) format(mean(x),format = "%H:%M"))
    
    #  GM Avg.Start.Time
    #1 ED          14:43
    #2 LD          15:05
    

    【讨论】:

      【解决方案3】:

      我们可以使用data.table

      library(data.table)
      setDT(copy1)[,.(Avg.Start.Time = mean(as.POSIXct(Avg.Start.Time, format = "%M:%S")))  , GM]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 1970-01-01
        • 2022-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多