Search code examples
rtidyversedata-manipulation

String split across multiple position delimiters in R


I am having some trouble splitting text between delimiters and need to be specific about which delimiters I choose from.

Consider the following:

a <- "hello, my, name, is, monty, and, i, would, like, something, to, drink"

Lets say I want to extract the text "monty" which sits between delimiters 4 and 5 (which are both commas), how would I go about doing this extraction?

I have tried str_extract to extract "hello" but this is based on the text before the first occurrence of the comma.

Thanks in advance for any answers


Solution

  • I'd use stringr's string_split to produce a list then extract the 5th item:

    stringr::str_split(a, pattern = ", ")[[1]][5]
    [1] "monty"