4

我的数据框中有两个字符变量,start_time并且stop_time

  start_time     stop_time
        <chr>        <chr>   
1     19:5:00     19:11:00 
2    20:33:37     20:34:39
3    20:23:00     20:23:38
4    20:12:00     20:13:00
5    20:00:39     20:00:39

我想计算和之间的start_time差异stop_time用 dplyr 计算分钟数我的问题是这两个变量都表示为一个字符。

预期输出:

    diff_time    
        <dbl>         
1           6     
2         1.2    
3        0.38     
4           1   
5        0.39
4

3 回答 3

3
library(dplyr)
library(lubridate)

df1 %>% 
  mutate(duration = seconds_to_period(as.numeric(difftime(
                                            strptime(stop_time, "%H:%M:%S"), 
                                            strptime(start_time, "%H:%M:%S"), 
                             units = "secs"))))

#>   start_time stop_time duration
#> 1    19:5:00  19:11:00    6M 0S
#> 2   20:33:37  20:34:39    1M 2S
#> 3   20:23:00  20:23:38      38S
#> 4   20:12:00  20:13:00    1M 0S
#> 5   20:00:39  20:00:39       0S

数据:

read.table(text="  start_time     stop_time
19:5:00     19:11:00 
20:33:37     20:34:39
20:23:00     20:23:38
20:12:00     20:13:00
20:00:39     20:00:39", stringsAsFactors=F, header=T) -> df1
于 2019-10-29T16:43:58.830 回答
1

您可以使用以下代码段来计算时差并转换为时间对象:

as.numeric(difftime(strptime(paste("19:11:00"),"%H:%M:%S"),
                    strptime(paste("19:5:00"),"%H:%M:%S")))

输出:

[1] 6
于 2019-10-29T16:41:28.163 回答
1

你可以试试:

library(lubridate)
data_time <- data.frame(start_time = c("19:5:00","20:33:37","20:23:00","20:12:00","20:00:39"),
                    stop_time =   c("19:11:00","20:34:39","20:23:38","20:13:00","20:00:39"), stringsAsFactors = FALSE)

data_time$difference <- difftime(as.POSIXct(data_time$stop_time, format = "%H:%M:%S"), 
                             as.POSIXct(data_time$start_time, format = "%H:%M:%S"), 
                             units = "mins")

问候,

亚历克西斯

于 2019-10-29T16:55:45.577 回答