Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 在|之间提取最后一个单词|_Regex_R_Stringr - Fatal编程技术网

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)