【问题标题】:How can I convert MM::SS string into HMS format如何将 MM::SS 字符串转换为 HMS 格式
【发布时间】:2021-09-08 02:53:51
【问题描述】:

我有以下数据框:

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

【问题讨论】:

  • @ViníciusFélix 不完全是。这就是为什么我再次提出一个新的。我特别需要 hms::as_hms 格式。
  • 请在主帖中指定您的最终目标。您是否只想将tm 更改为hms::as_hms 格式?是这样吗?
  • @RonakShah 是的!只是为了改成 hms::as_hms 格式。
  • @ViníciusFélix hms_df 是我希望我的df 成为的最终格式。我在我的OP中说得很清楚。
  • 您是否也必须提供时间,例如 as_hms(paste0("00:", df$tm)) ?帮助文件?as_hms 似乎暗示了这种情况 - “对于 hms,所有参数必须具有相同的长度或为 NULL。奇数组合(例如,仅传递秒和小时但不传递分钟)被拒绝。 i>"

标签: r time dplyr tidyverse


【解决方案1】:

函数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

【讨论】:

    【解决方案2】:

    as.PosIXct 然后as_hms 有效

    hms::as_hms(as.POSIXct(df$tm, format = "%M:%S"))
    
    00:30:15
    00:29:18
    00:30:38
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      相关资源
      最近更新 更多