How to create pair of vector that are complementary to each other based on source vector in R

1870 views r

I have the following source vector:

source_vec <- c(1:3)

What I want to do is to enumerate the vector by splitting into two when one value is selected the other vector is complementary. Finally, it'll look like this (do by hand):

  from  to
  1,2    3
  1,3    2
  2,3    1

Note that the to column only one value, but from can be many.

Ideally, the final output is a dataframe/tibble, but from column is a list column.

How can I achieve that with R?

answered question
Add a Comment

1 Answer

akrun 0 Comments

Here is an option with base R

m1 <- combn(source_vec, 2)
apply(m1, 2, function(x) list(x, setdiff(source_vec, x)))

posted this

Please login first before posting an answer.