如何将MM::SS字符串转换为时间格式并对其进行操作 [英] How to convert MM::SS string to time format and then manipulate it

查看:23
本文介绍了如何将MM::SS字符串转换为时间格式并对其进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

library(tibble)
dat <- structure(list(title = c("Title A", "Title B", "Title C"), tm = c(
  "31:17",
  "30:28", "32:06"
)), row.names = c(NA, -3L), spec = structure(list(
  cols = list(title = structure(list(), class = c(
    "collector_character",
    "collector"
  )), tm = structure(list(), class = c(
    "collector_character",
    "collector"
  ))), default = structure(list(), class = c(
    "collector_guess",
    "collector"
  )), delim = ","
), class = "col_spec"), class = c(
  "spec_tbl_df",
  "tbl_df", "tbl", "data.frame"
))

如下所示:

> dat
# A tibble: 3 × 2
  title   tm   
  <chr>   <chr>
1 Title A 31:17
2 Title B 30:28
3 Title C 32:06

第二列是时间,但作为字符。我想做的是 每行增加5分钟;结果为:

  Title A 36:17
  Title B 35:28
  Title C 37:06

策略是先将tm转换为数字形式。但此步骤失败

dat %>% 
  mutate(nt = hms::as_hms(as.numeric(tm) + 5))

它给了我:

  title   tm    nt    
  <chr>   <chr> <time>
1 Title A 31:17    NA 
2 Title B 30:28    NA 
3 Title C 32:06    NA 

做这件事的正确方法是什么?

推荐答案

使用lubridate-

library(dplyr)
library(lubridate)

dat %>% 
  mutate(tm = ms(tm) + minutes(5), 
         tm_string = sprintf('%02d:%02d', tm@minute, tm@.Data)) 

#  title   tm       tm_string
#  <chr>   <Period> <chr>    
#1 Title A 36M 17S  36:17    
#2 Title B 35M 28S  35:28    
#3 Title C 37M 6S   37:06    

这篇关于如何将MM::SS字符串转换为时间格式并对其进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆