如何将R中的字符时间更改为数字时间

如何将R中的字符时间更改为数字时间,r,R,我有这样一个字符变量: "1h 3m 6s 0h 13m 30s 0h 15m 12s" 所需的输出正在转换为数字秒。我应该怎么做?我们需要在小时之前将单个字符串转换为子字符串(使用strsplit),相应地将“h”、“m”、“s”替换为3600、60和1,并进行计算以获得秒的输出 library(gsubfn) str2 <- strsplit(str1, "\\s(?=\\d+h)", perl = TRUE)[[1]] 如果我们使用的是lubridate,则在拆分

我有这样一个字符变量:

"1h 3m 6s
 0h 13m 30s
 0h 15m 12s"

所需的输出正在转换为数字秒。我应该怎么做?

我们需要在小时之前将单个字符串转换为子字符串(使用
strsplit
),相应地将“h”、“m”、“s”替换为3600、60和1,并进行计算以获得秒的输出

library(gsubfn)     
str2 <- strsplit(str1, "\\s(?=\\d+h)", perl = TRUE)[[1]]

如果我们使用的是
lubridate
,则在拆分字符串并将其转换为
period
类和
as.period

library(lubridate)
period_to_seconds(as.period(toupper(str2)))
#[1] 3786  810  912
数据
str1您试图解决这个问题的方法是什么?
unname(sapply(gsubfn("([a-z]+)", list(h = " * 3600", m = " * 60", s = " * 1"), 
        gsub(" ", " + ", str2)), function(x) eval(parse(text = x))))
#[1] 3786  810  912
library(lubridate)
period_to_seconds(as.period(toupper(str2)))
#[1] 3786  810  912
str1 <- "1h 3m 6s 0h 13m 30s 0h 15m 12s"