如何从一个模式后面的一列插入字符到另一列?

问题描述 投票:0回答:2

假设我有一个看起来像这样的数据集。

                Name  Time
ABC_something_month1    NA
ABD_something_month2    NA
ABD_something_month1    NA

我将如何编写代码来搜索'month',并在时间列中插入以下数字,使其看起来像这样

                Name  Time
ABC_something_month1     1
ABD_something_month2     2
ABD_something_month1     1
r search
2个回答
1
投票

提取"month"后的数字

df$Time <- sub('.*month(\\d+)', '\\1', df$Name)
df
#                  Name Time
#1 ABC_something_month1    1
#2 ABD_something_month2    2
#3 ABD_something_month1    1

或使用str_extract

df$Time <- stringr::str_extract(df$Name, '(?<=month)\\d+')

0
投票

我们可以使用parse_number中的readr

library(readr)
library(dplyr)
df %>%
  mutate(Time = parse_number(Name))

library(stringr)
df %>%
    mutate(Time = str_remove_all(Name, "\\D+"))
© www.soinside.com 2019 - 2024. All rights reserved.