8

I have the following dataset

> 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|" 

I want to extract the last word between || as a new variable i.e.

Acinetobacter
Bacillus
Haemophilus

I have tried using

library(stringr)
names$sample2 <-   str_match(names$SAMPLE_ID, "|.*?|")
Keniajin
  • 1,649
  • 2
  • 20
  • 43

5 Answers5

5

We can use

library(stringi)
stri_extract_last_regex(v1, '\\w+')
#[1] "Acinetobacter"

data

v1 <- "Bacteria|Proteobacteria|Gammaproteobacteria|Pseudomonadales|Moraxellaceae|Acinetobacter|"
akrun
  • 874,273
  • 37
  • 540
  • 662
5

Using just base R:

myvar <- gsub("^..*\\|(\\w+)\\|$", "\\1", names$SAMPLE_ID)
Zelazny7
  • 39,946
  • 18
  • 70
  • 84
3
^.*\\|\\K.*?(?=\\|)

Use \K to remove rest from the final matche.See demo.Also use perl=T

https://regex101.com/r/fM9lY3/45

x <- c("Bacteria|Firmicutes|Bacilli|Lactobacillales|Streptococcaceae|Streptococcus|",
       "Bacteria|Firmicutes|Bacilli|Lactobacillales|Streptococcaceae|Streptococcus|" )

unlist(regmatches(x, gregexpr('^.*\\|\\K.*?(?=\\|)', x, perl = TRUE)))
# [1] "Streptococcus" "Streptococcus"
rawr
  • 20,481
  • 4
  • 44
  • 78
vks
  • 67,027
  • 10
  • 91
  • 124
3

The ending is all you need [^|]+(?=\|$)

Per @RichardScriven :

Which in R would be regmatches(x, regexpr("[^|]+(?=\\|$)", x, perl = TRUE)

1

You can use package "stringr" as well in this case. Here is the code:

v<- "Bacteria| Proteobacteria|Gammaproteobacteria|Pseudomonadales|Moraxellaceae|Acinetobacter|"

v1<- str_replace_all(v, "\\|", " ")

word(v1,-2)

Here I used v as the string. The basic theory is to replace all the | with spaces, and then get the last word in the string by using function word().

Frankie
  • 61
  • 3