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").
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With