我有这个Identifier专栏
structure(list(Identifier = c("NC.1.OA", "NC.1.OA.0", "NC.1.OA.1",
"NC.1.OA.1.a", "NC.1.OA.1.b", "NC.1.OA.1.c", "NC.1.OA.2", "NC.1.OA.2.0",
"NC.1.OA.3", "NC.1.OA.4", "NC.1.OA.4.0", "NC.1.OA.9", "NC.1.OA.6",
"NC.1.OA.6.a", "NC.1.OA.6.b", "NC.1.OA.6.c", "NC.1.OA.6.d", "NC.1.OA.6.e",
"NC.1.OA.6.f", "NC.1.OA.6.f.0", "NC.1.OA.7", "NC.1.OA.8")), row.names = c(NA,
-22L), class = c("tbl_df", "tbl", "data.frame"))我想从这个专栏中提取出NC.1.OA。通常,这将提取从开始到第三个周期的所有内容,但是第一行将违反这一点,因为只有两个周期。
我试过没有雪茄的gsub(".*\\.(.*)\\..*", "\\1", Identifier)。
发布于 2018-11-14 17:55:52
我们可以使用str_extract
library(tidyverse)
df %>%
mutate(new = str_extract(Identifier, "NC\\.1\\.OA"))另外,如果我们使用的是sub (不需要gsub,因为我们不需要全局替换),那么使用一个位置标识符来通知字符串的开始(^)。在下面的模式中,我们匹配一个或多个字符,这些字符不是. ([^.]+),后面是. ([.] -[.]是元字符,因此我们将其转义或放在方括号中以按字面计算),然后再匹配一个数字(\\d+),然后是.和不是点的字符(与前面一样),捕获为一个组(用括号包装),并在替换中使用捕获组的反向引用(\\1)。
sub("^([^.]+[.]\\d+[.][^.]+).*", "\\1", df$Identifier)
#[1] "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA"
#[12] "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA" "NC.1.OA"https://stackoverflow.com/questions/53306163
复制相似问题