recognize a specific element order pattern in R vector

Viewed 65

I have a list of vectors that each vector look like this

c("Japan", "USA", "country", "Japan", "source", "country", "UK", "source", "country", "USA")

My task is to extract the country name after the first c("source", "country"), so "UK" will be the country name to be extracted in this example. In all vectors, c("source", "country") will be followed by a country name, so I just need to extract the element right after the first c("source", "country").

2 Answers

We could try using a paste collapse regex approach here:

v <- c("Japan", "USA", "country", "Japan", "source", "country", "UK", "source", "country", "USA")
terms <- paste(v, collapse="|")
country <- sub("^.*?\\|source\\|country\\|(.*?)\\|.*$", "\\1", terms)
country

[1] "UK"

The approach used here is to form a pipe-delimited list of terms, looking like:

Japan|USA|country|Japan|source|country|UK|source|country|USA

Then, we search for the first |source|country| occurrence and retain the term coming immediately after that.

You can use the following to find the first index of where source comes before country and add 2:

x <- c("Japan", "USA", "country", "Japan", "source", "country", "UK", "source", "country", "USA")

x[which((x == "source")[-length(x)] & (x == "country")[-1])[1] + 2]
# [1] "UK"
Related