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.
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.
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.
Many thanks in advance
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With