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

问题描述

我有一串字符串,其长度为句点,格式为"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,x)),function(x) sum(as.numeric(x) * c(12,1)) )  
}
,

要以您的substr尝试为基础:几个月以来,您可以从字符串末尾定义startstop,以避免因数字而不同的开始/停止位置的问题月和年的数字位数

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

另一种非正则表达式替代方法:

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