Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recognize a specific element order pattern in R vector

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

like image 645
kelvinfrog Avatar asked Mar 15 '26 19:03

kelvinfrog


1 Answers

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"
like image 152
Ritchie Sacramento Avatar answered Mar 18 '26 09:03

Ritchie Sacramento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!