2

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,753
  • 72
  • 57
  • 129
Remi.b
  • 17,389
  • 28
  • 87
  • 168

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
  • 65,572
  • 8
  • 165
  • 155