简体   繁体   中英

Finding Index of Common Elements in Multiple Vectors in R

From other stack overflow posts, I figured out the following code can be used to find the common values between multiple vectors (eg a, b):

Reduce(intersect, list(a,b,...))

I could not figure out a good way to get the common value indices from the vectors. Any help would be appreciated.

Here is an example of the desired input and output:

a <- c(5,2)
b <- c(5,3)
d <- c(4,5)

Common value index between a and b should be 1, since both vectors have 5 at that index. For finding common value index between a and d, the method should return 1 for a and 2 for d.

a <- c(5,2); b <- c(5,3); d <- c(4,5)
mylist = list(a = a, b = b, d = d)  #OR  mylist = mget(c("a", "b", "d"))
common_values = Reduce(intersect, mylist)
lapply(mylist, function(x) which(x %in% common_values))
#$a
#[1] 1

#$b
#[1] 1

#$d
#[1] 2

It is not clear how you want to address when there can be more than one common value, but here is one way

a = 1:3
b = 2:4
d = c(2, 7, 3, 5)
mylist = mget(c("a", "b", "d"))
common_values = Reduce(intersect, mylist)
lapply(mylist, function(x)
    sapply(setNames(common_values, common_values), function(y)
        which(x %in% y)))
#$a
#2 3 
#2 3 

#$b
#2 3 
#1 2 

#$d
#2 3 
#1 3 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM