从字符串中提取以年和月为单位的持续时间并转换为月

Extract duration in years and months from string and convert to months

我有一个长度为句点的字符串列,格式为 "xx years yy months"。我只想用月来表示这些时间段,即 12 * 年数 + 月数。

一个小例子:

x = c("2 years 5 months", "10 years 10 months")

这里想要的结果分别是2 * 12 + 5 = 29,和10 * 12 + 10 = 130。


我尝试了 substr 函数,但我无法处理月份和年份可能是一位或两位数的事实。

12 * as.numeric(substr(x, 1, 2)) + as.numeric(substr(x, 6, 7)))

然后我尝试了如下 sprintf,但没有给出预期的结果。

sprintf("%1.0f", x))

使用正则表达式提取年数和月数可以这样实现:

tomonths <- function(x) {
  sum(as.numeric(regmatches(x, gregexpr("\d+", x))[[1]]) * c(12, 1))  
}
tomonths("10 years 10 months")
#> [1] 130

对于您可能会使用的向量,例如sapply(c("2 years 5 months", "10 years 10 months"), tomonths).

编辑:根据@thelatemail 的评论(谢谢!)矢量化和更有效的方法如下所示:

tomonths2 <- function(x) {
  sapply(regmatches(x, gregexpr("\d+", x)), function(x) sum(as.numeric(x) * c(12,1)) )  
}

在你的 substr 尝试的基础上:几个月来,你可以从字符串的末尾定义 startstop 以避免不同 start/stop 的问题位置取决于月份和年份的位数

as.integer(substr(x, 1, 2)) * 12 + as.integer(substr(x, nchar(x) - 8, nchar(x) - 6))
# [1]  29 130 

另一个non-regex备选方案:

sapply(strsplit(x, " "), function(v) sum(as.integer(v[c(1, 3)]) * c(12, 1)))
# [1]  29 130

使用 lubridate 便利函数:

library(lubridate)
time_length(duration(x), unit = "months")
# [1]  29 130