簡體   English   中英

在R中的多個向量中找到公共元素的索引

[英]Finding Index of Common Elements in Multiple Vectors in R

從其他堆棧溢出帖子中,我發現以下代碼可用於查找多個向量(例如a,b)之間的公共值:

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

我想不出一種從向量中獲取共同價值指數的好方法。 任何幫助,將不勝感激。

這是所需輸入和輸出的示例:

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

a和b之間的公共價值指數應為1,因為兩個向量在該指數處均具有5。 為了找到a和d之間的公共價值指數,該方法應該為a返回1,為d返回2。

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

目前尚不清楚在存在多個共同值時您要如何解決,但這是一種方法

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM