简体   繁体   English

提取R中混合月份和年份字符串的总月数

[英]Extract total number of months of strings of mixed months and years in R

I have a dataframe that includes a column with values like:我有一个 dataframe 包含一列,其值如下:

"Sentenced to 2years and 90 years" “判处2年和90年”
"Sentenced to 5years and 6months" “被判5年6个月”
"Sentenced to 3months" “被判3个月”

I need to only get the total number of months for each of them, how can I do this?我只需要获得每个人的总月数,我该怎么做?

"Sentenced to 2years and 90 years" would give 1104 "Sentenced to 5years and 6months" would give 66 "Sentenced to 3months" would give 3 “判处 2 年和 90 年”将给出 1104 “判处 5 年和 6 个月”将给出 66 “判处 3 个月”将给出 3

Does this give you the expected result?这会给你预期的结果吗?

library(stringr)
my_year <- str_extract_all(string = "Sentenced to 5years and 6month", pattern = "[0-9]+ ?years?", simplify = TRUE)
my_month <- str_extract_all(string = "Sentenced to 5years and 6month", pattern = "[0-9]+ ?months?", simplify = TRUE)


my_year <- sum(as.double(str_extract(string = my_year, pattern = "[0-9]+"))) * 12
my_month <- sum(as.double(str_extract(string = my_month, pattern = "[0-9]+")))

my_result <- my_year + my_month

One extract for the years and one for the month, then we just multiply the number of years per 12 since there are 12 months in a year and we add the months we extracted一个提取年份,一个提取月份,然后我们只需将每 12 的年数相乘,因为一年中有 12 个月,然后我们将提取的月份相加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM