This is a variation of a question previously posted here. R - A loop comparing elements in common between two hierarchical lists I figured this problem might present sufficient alteration in its solution form, hence a new post.
I would like to retrieve a list of the elements in common when comparing two lists, hierarchically structured (sites contain groups, which contain elements)
Here is some dummy data:
site<-c('A','A','A','A','A','A','A','A','A','B','B','B','B','B','B')
group<-c('A1','A1','A2','A2','A2','A3','A3','A3','A3',
'B1','B1','B2','B2','B2','B2')
element<-c("red","orange","blue","black","white", "black","cream","yellow","purple","red","orange","blue","white","gray","salmon")
d<-cbind(site,group,element)
The twist is that I don´t want every possible comparison between groups, but only between sites. Hence, I organized the data in such manner.
#first level list - by site
sitelist<-split(d, list(d$site),drop = TRUE)
#list by group
nestedlist <- lapply(sitelist, function(x) split(x, x[['group']], drop = TRUE))
My intention is to create a list with the element in common between groups from the two sites (my original data has additional sites). Therefore, if the data being structured as such:
A1 A2 A3
B1 2 0 0
B2 0 2 0
I need the list of elements appearing in the intersection of A1/B1, and A2/B2. Therefore the outuput being:
output
$A1-B1
[1] "red" "orange"
$A2-B2
[2] "blue" "white"
My attempt is similar to what was posted in the previous related question, with adjustments of what I comprehend as being what would work.
t <- outer(1:length(d$A),
1:length(d$B),
FUN=function(i,j){
sapply(1:length(i),
FUN=function(x)
intersect(d$A[[i]]$element, d$B[[j]]$element) )
})
Again, any help is much appreciated, and apologies if this is too similar of a question. My attempts at tweaking all of the suggestions have failed.