Intersect all possible combinations of list elements

后端 未结 3 477
面向向阳花
面向向阳花 2020-12-17 18:13

I have a list of vectors:

> l <- list(A=c(\"one\", \"two\", \"three\", \"four\"), B=c(\"one\", \"two\"), C=c(\"two\", \"four\", \"five\", \"six\"), D=c         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 18:55

    combn works with list structures as well, you just need a little unlist'ing of the result to use intersect...

    # Get the combinations of names of list elements
    nms <- combn( names(l) , 2 , FUN = paste0 , collapse = "" , simplify = FALSE )
    
    # Make the combinations of list elements
    ll <- combn( l , 2 , simplify = FALSE )
    
    # Intersect the list elements
    out <- lapply( ll , function(x) length( intersect( x[[1]] , x[[2]] ) ) )
    
    # Output with names
    setNames( out , nms )
    #$AB
    #[1] 2
    
    #$AC
    #[1] 2
    
    #$AD
    #[1] 0
    
    #$BC
    #[1] 1
    
    #$BD
    #[1] 0
    
    #$CD
    #[1] 1
    

提交回复
热议问题