假设我有一个看起来像这样的数据集。
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
提取"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+')
我们可以使用parse_number
中的readr
library(readr)
library(dplyr)
df %>%
mutate(Time = parse_number(Name))
library(stringr)
df %>%
mutate(Time = str_remove_all(Name, "\\D+"))