r - 将变量中的数字与字符分开,长度不一致 -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 个月来代替它
解决方案
一种选择是基于正则表达式环视进行提取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")
推荐阅读
- wildfly - 您可以在wildfly 上为microprofile-health 端点配置端口吗?
- zsh - Zsh - 完全删除当前/上一个参数
- list - 创建所有可能的地图
> 从列表中 - javascript - Split a string on a capital letter or numbers
- python - 仅显示一个元素的绘图图例
- python - python根据属性跳过单元测试
- python - Python中的抽象类,添加有和没有实现的方法是否错误
- google-analytics - 如果我使用屏蔽 URL,我如何分隔同一域的 Google Analytics?
- c++ - 如何使用 CMake 将 C++ 编译为 CUDA
- excel - 尝试读取 Comment 属性时出现运行时错误 438