find common elements among several vectors with R and apply a function -
i r newbie , make question, although title similar other posted questions didn't find solution in them.
my question following: have several vectors different lengths , compare them in pairwise manner , apply function each comparison generating value of common elements between vectors, example 4 vectors named a, b, c, d find common elements between , b, , c, , d, b , c, b , d, c , d.
a more detailed example here (only 2 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 function apply each comparison. 0.4 #value returned function i have large number of vectors , don't know how implement loop in order make pairwise comparisons.
many in advance
you can use outer
baseset <- c('t','qt','er','oa','qra','ea','ew','ee','qwt') set.seed(0) <- 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)) # 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
Comments
Post a Comment