Search code examples
rregexstringdelimiter

r identify and return string prior to last delimiter


I have found similar questions on stackoverflow, but not exactly what I'm looking for. I have a vector like:

x <- c('w/x/y/z', 'x/y/z', 'y/z')

I want to return a vector that gives me the string (in my real data, a longer string than 1 letter) that is before the last / and prior to any other /. So, the output for this would be:

y <- c('y', 'y', 'y')

I have tried using strsplit and tail to split by / and return the last 2 items, but don't know how to only get the second to last item.

y <- sapply(lapply(spl, tail,2), paste, collapse = '/')
y
[1] "y/z" "y/z" "y/z"

Solution

  • ifelse(grepl("/", x), sapply(strsplit(x, "/"), function(S) tail(S, 2)[1]), NA)
    #[1] "y" "y" "y"