[英]How to change character time to numeric time in R
我有一個像這樣的字符變量:
"1h 3m 6s
0h 13m 30s
0h 15m 12s"
所需的輸出正在轉換為數字秒。 我該怎么辦?
我們需要在小時前的空格處將單個字符串轉換為子字符串(使用strsplit
),將 'h'、'm'、's' 分別替換為strsplit
和 1,並進行評估以獲得輸出作為秒
library(gsubfn)
str2 <- strsplit(str1, "\\s(?=\\d+h)", perl = TRUE)[[1]]
如果字符串分隔是換行符,則執行
str2 <- strsplit(str1, "\n\\s")[[1]]
使用gsubfn
替換 'h'、'm'、's' 值並稍后評估
unname(sapply(gsubfn("([a-z]+)", list(h = " * 3600", m = " * 60", s = " * 1"),
gsub(" ", " + ", str2)), function(x) eval(parse(text = x))))
#[1] 3786 810 912
如果我們使用lubridate
的period_to_seconds
可以拆分后的字符串中使用並將其轉換為一個Period
與類as.period
library(lubridate)
period_to_seconds(as.period(toupper(str2)))
#[1] 3786 810 912
str1 <- "1h 3m 6s 0h 13m 30s 0h 15m 12s"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.