首页 > 解决方案 > 如何将 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 

正确的方法是什么?

标签: rtimetidyverse

解决方案


使用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    

推荐阅读