How to find the position of equal elements in character vectors (Character)?

Asked

Viewed 1,174 times

1

Considering:

a<-c("Ano", "X2751006.", "X2751007.", "X2751008.", "X2751015.", 
     "X2751017.", "X2751018.", "X2751025.", "X2752001.", "X2752006.", 
     "X2752007.", "X2752008.", "X2752009.", "X2752010.", "X2752011.", 
     "X2752012.", "X2752013.", "X2752014.", "X2752017.", "X2752021.", 
     "X2753001.", "X2753002.", "X2753003.", "X2753004.", "X2753005.", 
     "X2753007.", "X2753008.", "X2753009.", "X2753014.")

 b<-c( "X2752013.", "X2752014.","X2753014.")

What function should I apply to know the position of b in a, utilizing R?

NOTE: I applied the function which and grep and I was unsuccessful.

1 answer

4


If you seek elements in a who are exactly equal to the elements in b, the best option is to use %in%:

a<-c("Ano", "X2751006.", "X2751007.", "X2751008.", "X2751015.", 
     "X2751017.", "X2751018.", "X2751025.", "X2752001.", "X2752006.", 
     "X2752007.", "X2752008.", "X2752009.", "X2752010.", "X2752011.", 
     "X2752012.", "X2752013.", "X2752014.", "X2752017.", "X2752021.", 
     "X2753001.", "X2753002.", "X2753003.", "X2753004.", "X2753005.", 
     "X2753007.", "X2753008.", "X2753009.", "X2753014.")

 b<-c( "X2752013.", "X2752014.","X2753014.")

a %in% b
which(a %in% b)

If you want to search for regular expressions, one option is to combine mapply(), grepl(), apply() and unlist():

apply(unlist(mapply(grepl, a, MoreArgs = list(b))), 1, which)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.