【问题标题】:Splitting a time-representing string and extracting value in seconds拆分表示时间的字符串并以秒为单位提取值
【发布时间】:2021-01-23 15:49:00
【问题描述】:

我正在尝试编写一个函数,该函数需要像“mm:ss.sss”这样的字符串(例如 1:23.242)并返回总秒数(在本例中为 83.242)。

这是我的尝试:

get_time <- function(str){
  minutes = strsplit(str,split=":")[0]
  seconds = strsplit(str,split=":")[1]
  return((60.0)*as.numeric(minutes)+as.numeric(seconds))
}

我认为 strsplit 函数存在一些问题。我知道it returns a list,但是通过[] 访问元素似乎不起作用,即使他们在the tutorial 中这么说。

我做错了什么?

【问题讨论】:

  • 两件事:(1)strsplit返回一个列表,所以你可以尝试使用unlist如下:unlist(strsplit(str, split = ":")) ...和(2)R是1索引(不是0 -indexed),所以你需要[1] 分钟和[2] 几秒钟......将两者放在一起你将拥有minutes = unlist(strsplit(str,split=":"))[1]seconds = unlist(strsplit(str,split=":"))[2]......
  • 另外,关于子集列表,请查看this reference。在您的情况下,您可以通过多种方式进行子集化,而不使用 unlist...例如 [[c(1,1)]] 分钟和 [[c(1,2)]] 秒...
  • 谢谢,问题已经解决了:)

标签: r string time


【解决方案1】:

lubridate 包中的一些函数可以为您完成很多工作。下面是一些使用 ms 函数读取分钟和秒的示例代码。

library(lubridate)
timestring <- '1:23.242'
ms <- ms(timestring)
seconds <- as.numeric(as.duration(ms))
seconds
# [1] 83.242

【讨论】:

    【解决方案2】:

    这是另一种方法:

    > as.numeric(unlist(str_split('1:23.56', ":"))) %*% c(60,1)
          [,1]
    [1,] 83.56
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      相关资源
      最近更新 更多