如何将 MM::SS 字符串转换为 HMS 格式

How can I convert MM::SS string into HMS format

我有以下数据框:

df <- structure(list(tm = c("30:15", "29:18", "30:38")), row.names = c(NA, 
-3L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), 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"))

看起来像这样(列格式为字符):

 tm   
  <chr>
1 30:15
2 29:18
3 30:38

我想做的是从hms包转换成hms::as_hms格式。

# this is a dput from text parsing package
hms_df <- structure(list(tm = structure(c(108900, 105480, 110280), class = c("hms", 
"difftime"), units = "secs")), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

像这样:

 tm    
  <time>
1 30:15 
2 29:18 
3 30:38 

为什么此代码不起作用

df %>% 
 mutate(tm = hms::as_hms(tm))

它给出:

Error: Problem with `mutate()` column `ntm`.
ℹ `ntm = hms::as_hms(tm)`.
x Lossy cast from <character> to <hms> at position(s) 1, 2, 3

as.PosIXct 然后 as_hms 有效

hms::as_hms(as.POSIXct(df$tm, format = "%M:%S"))

00:30:15
00:29:18
00:30:38

函数hms需要小时、分钟和秒。在数据中你只有分和秒。您可以附加虚拟 '00' 值作为小时数。

library(dplyr)

df <- df %>% mutate(tm = hms::as_hms(sprintf('00:%s', tm))) 
df

#   tm    
#  <time>
#1 30'15"
#2 29'18"
#3 30'38"

df$tm
#00:30:15
#00:29:18
#00:30:38