首页 > 解决方案 > 将变量中的数字与字符分开,长度不一致 -R

问题描述

我正在尝试计算几个月的经验,但目前我的变量如下所示,其中年份和月份在同一列中。

2 yrs 1 mo
1 yr 1 mo
2 yrs 4 mos
less than a year
10 mos

我想将年份和月份分开,这样我就可以计算总经验月数。到目前为止,我的尝试并不优雅,substring也不是很有帮助,因为长度不一致。知道我该怎么做吗?

编辑:对于less than a year,我想用 11 个月来代替它

标签: rsubstring

解决方案


一种选择是基于正则表达式环视进行提取str_extract,然后计算“total_month”。less than a year在 OP 的帖子中更新为“11 mo ”

library(dplyr)
library(stringr)
library(tidyr)
dat %>%
   mutate(col1 = replace(col1, col1 == 'less than a year', '11 mos'),
          month = as.numeric(str_extract(col1, "\\d+(?= mo)")),
          year = replace_na(as.numeric(str_extract(col1, "\\d+(?= yr)")), 0), 
          totalmonth = month + year * 12)
#         col1 month year totalmonth
#1  2 yrs 1 mo     1    2         25
#2   1 yr 1 mo     1    1         13
#3 2 yrs 4 mos     4    2         28
#4      11 mos    11    0         11
#5      10 mos    10    0         10

或者另一种选择是利用extract

dat %>%
    mutate(col1 = case_when(col1 == 'less than a year' ~ '0 yr 11 mos',
           str_detect(col1, '^\\d+\\s+mo')~ str_c('0 yr ', col1), TRUE ~ col1)) %>%
    extract(col1, into = c('year', 'month'),   "^(\\d+)\\s*yrs?\\s*(\\d+).*",
             convert = TRUE, remove = FALSE) %>% 
    mutate(totalmonth = month + year * 12)

数据

dat <- structure(list(col1 = c("2 yrs 1 mo", "1 yr 1 mo", "2 yrs 4 mos", 
"less than a year", "10 mos")), row.names = c(NA, -5L), class = "data.frame")

推荐阅读