Regex 在|之间提取最后一个单词|
我有以下数据集Regex 在|之间提取最后一个单词|,regex,r,stringr,Regex,R,Stringr,我有以下数据集 > head(names$SAMPLE_ID) [1] "Bacteria|Proteobacteria|Gammaproteobacteria|Pseudomonadales|Moraxellaceae|Acinetobacter|" [2] "Bacteria|Firmicutes|Bacilli|Bacillales|Bacillaceae|Bacillus|" [3] "Bacteria|Proteobacte
> head(names$SAMPLE_ID)
[1] "Bacteria|Proteobacteria|Gammaproteobacteria|Pseudomonadales|Moraxellaceae|Acinetobacter|"
[2] "Bacteria|Firmicutes|Bacilli|Bacillales|Bacillaceae|Bacillus|"
[3] "Bacteria|Proteobacteria|Gammaproteobacteria|Pasteurellales|Pasteurellaceae|Haemophilus|"
[4] "Bacteria|Firmicutes|Bacilli|Lactobacillales|Streptococcaceae|Streptococcus|"
[5] "Bacteria|Firmicutes|Bacilli|Lactobacillales|Streptococcaceae|Streptococcus|"
[6] "Bacteria|Firmicutes|Bacilli|Lactobacillales|Streptococcaceae|Streptococcus|"
我想提取|
之间的最后一个单词作为新变量,即
Acinetobacter
Bacillus
Haemophilus
我试过使用
library(stringr)
names$sample2 <- str_match(names$SAMPLE_ID, "|.*?|")
库(stringr)
名称$sample2
使用\K
从最终匹配中删除剩余部分。请参阅演示。也可以使用perl=T
x我们可以使用
library(stringi)
stri_extract_last_regex(v1, '\\w+')
#[1] "Acinetobacter"
数据
v1仅使用基本R:
myvar <- gsub("^..*\\|(\\w+)\\|$", "\\1", names$SAMPLE_ID)
myvar结尾就是你所需要的一切[^ |]+(?=\\|$)
每@RichardScriven:
在R中哪个是regmatches(x,regexpr([^ |]+(?=\\\\\$)”,x,perl=TRUE)
在这种情况下,您也可以使用包“stringr”。下面是代码:
v简单的方法:vapply(strsplit(name$SAMPLE\u ID,“\124;”,fixed=TRUE),tail,“,1)
或者你不喜欢打字(或效率),那么sapply(strsplit(x,“\\\”),tail,1)
似乎stringi
包在某些方面比stringr
好。
library(stringi)
stri_extract_last_regex(v1, '\\w+')
#[1] "Acinetobacter"
v1 <- "Bacteria|Proteobacteria|Gammaproteobacteria|Pseudomonadales|Moraxellaceae|Acinetobacter|"
myvar <- gsub("^..*\\|(\\w+)\\|$", "\\1", names$SAMPLE_ID)