我正在试图计算经验的月份,但目前我的变量看起来类似于下面的内容,其中几年和几个月在同一栏中。
2 yrs 1 mo
1 yr 1 mo
2 yrs 4 mos
less than a year
10 mos我想把这几年和几个月分开,这样我就可以计算出经验的总月份。到目前为止,我的尝试是不优雅的,而且substring没有太大的帮助,因为长度不一致。知道我该怎么做吗?
编辑:对于less than a year,我想用11个月来代替它
发布于 2020-05-06 22:32:03
一种选择是使用str_extract基于regex查找执行提取,然后计算“total”。随着OP的更新,less than a year被更改为'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")https://stackoverflow.com/questions/61646451
复制相似问题