r - 从存储为字符的时间变量中获取时间差

标签 r dplyr difftime

我的数据框中有两个字符变量 start_timestop_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

最佳答案

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

关于r - 从存储为字符的时间变量中获取时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58611777/

相关文章:

python - 处理列中的多个值

r - 将常数乘以前一行并将结果累加到 R 中

r - 根据缺失行的宽数据计算出的时间差

r - 使用 difftime() 时如何提取时间单位?

r - 'quietly = TRUE' 什么时候在 require() 函数中真正起作用?

根据 R 中特定间隔内的列值删除重复项

r - 如何匹配两个数据帧的字符值并在 R 中应用与此匹配对应的函数?

r - R 中的 difftime 生成 NA 值

r - 具有不连续数据的分段线性回归

r - 使用 r (dplyr) 中的一组值进行过滤