【问题标题】:Separate numbers from characters in a variable, with inconsistent length -R将变量中的数字与字符分开,长度不一致 -R
【发布时间】:2023-03-26 04:50:01
【问题描述】:

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

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

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

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

【问题讨论】:

  • @akrun 我已经更新了帖子!

标签: r substring


【解决方案1】:

一种选择是使用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")

【讨论】:

  • 太棒了,str_extract 比这里的substring 更有意义
猜你喜欢
  • 2017-04-26
  • 2013-06-29
  • 2018-08-24
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多