1

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?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Remi.b
  • 16,247
  • 25
  • 74
  • 153

1 Answers1

1

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"
kohske
  • 63,256
  • 8
  • 159
  • 152