用R找到几个向量中的公共元素并应用一个函数

时间:2022-03-26 09:27:04

I am a R newbie and I would like to make a question, although the title is similar to other posted questions I didn't find the solution in them.

我是R新手,我想提出一个问题,虽然标题与其他已发布的问题类似但我没有找到解决方案。

My question is the following: I have several vectors with different lengths and I would like to compare them in a pairwise manner and apply a function to each comparison for generating a value of common elements between vectors, for example 4 vectors named A, B, C, D I would like to find common elements between A and B, A and C, A and D, B and C, B and D, C and D.

我的问题如下:我有几个不同长度的向量,我想以成对的方式比较它们,并为每个比较应用一个函数,以生成向量之间的共同元素的值,例如4个名为A,B的向量, C,DI希望找到A和B,A和C,A和D,B和C,B和D,C和D之间的共同元素。

A more detailed example here (only two vectors):

这里有一个更详细的例子(只有两个向量):

A=c("t","qt","er","oa","qra")
B=c("t","ea","ew","ee","oa","qwt") 
length(which(A%in%B))/min(length(A),length(B)) #this is the function I would like to apply to each comparison.
0.4 #value returned for the function

I have a large number of vectors and I don't know how to implement a for loop in order to make the pairwise comparisons.

我有大量的向量,我不知道如何实现for循环以进行成对比较。

Many thanks in advance

提前谢谢了

1 个解决方案

#1


4  

You can use outer

你可以使用外部

baseSet <- c('t','qt','er','oa','qra','ea','ew','ee','qwt')
set.seed(0)
A <- sample(baseSet, 5)
B <- sample(baseSet, 5)
C <- sample(baseSet, 5)
D <- sample(baseSet, 5)
dFun <- function(x,y){length(which(x%in%y))/min(length(x),length(y))}

outer(list(A,B,C,D), list(A,B,C,D),Vectorize(dFun))
#     [,1] [,2] [,3] [,4]
#[1,]  1.0  0.6  0.2  0.6
#[2,]  0.6  1.0  0.4  0.6
#[3,]  0.2  0.4  1.0  0.4
#[4,]  0.6  0.6  0.4  1.0

EDIT:

编辑:

list.df <- list(A=A, B=B, C=C, D=D)
outer(list.df, list.df, Vectorize(dFun))
#    A   B   C   D
#A 1.0 0.6 0.2 0.6
#B 0.6 1.0 0.4 0.6
#C 0.2 0.4 1.0 0.4
#D 0.6 0.6 0.4 1.0

#1


4  

You can use outer

你可以使用外部

baseSet <- c('t','qt','er','oa','qra','ea','ew','ee','qwt')
set.seed(0)
A <- sample(baseSet, 5)
B <- sample(baseSet, 5)
C <- sample(baseSet, 5)
D <- sample(baseSet, 5)
dFun <- function(x,y){length(which(x%in%y))/min(length(x),length(y))}

outer(list(A,B,C,D), list(A,B,C,D),Vectorize(dFun))
#     [,1] [,2] [,3] [,4]
#[1,]  1.0  0.6  0.2  0.6
#[2,]  0.6  1.0  0.4  0.6
#[3,]  0.2  0.4  1.0  0.4
#[4,]  0.6  0.6  0.4  1.0

EDIT:

编辑:

list.df <- list(A=A, B=B, C=C, D=D)
outer(list.df, list.df, Vectorize(dFun))
#    A   B   C   D
#A 1.0 0.6 0.2 0.6
#B 0.6 1.0 0.4 0.6
#C 0.2 0.4 1.0 0.4
#D 0.6 0.6 0.4 1.0