Search code examples
rlistinteraction

Looking for interactions of all elements of a list (in R)


I am looking for a function that takes one list (of numbers, characters or any kind of objects) and returns two vectors (or a list of vectors) which represents all possible interactions (we might apply the function table(..) on these outputs).

> my.fun(list(1,2)) # returns the following
> c(1)
> c(2)

> my.fun(list('a','b','c')) # returns the following
> c('a','a','b')
> c('b','c','c')

> my.fun(list('a','b','c','d')) # returns the following
> c('a','a','a','b','b','c')
> c('b','c','d','c','d','d')

Does it make sense?


Solution

  • Use combn:

    f <- function(L) {
      i <- combn(length(L), 2)
      list(unlist(L[i[1, ]]), unlist(L[i[2, ]]))
    }
    

    then,

    > f(list(1,2))
    [[1]]
    [1] 1
    
    [[2]]
    [1] 2
    
    > f(list('a','b','c'))
    [[1]]
    [1] "a" "a" "b"
    
    [[2]]
    [1] "b" "c" "c"
    
    > f(list('a','b','c','d'))
    [[1]]
    [1] "a" "a" "a" "b" "b" "c"
    
    [[2]]
    [1] "b" "c" "d" "c" "d" "d"