Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple combinatorics in R

I wish to share an R function for finding all possible unique undirected combinations between elements of a single vector:

combi <- function(vec1)
{
  si <- length(vec1)
  first <- rep(vec1, (si-1):0)
  secR <- rev(vec1)
  second <- secR[sequence(1:(si-1))]
  second <- rev(second)
  combi <- matrix(cbind(first, second), ncol = 2)
  return(combi)
}

and ask if there is a simpler way of doing this? (I need the result to be in a 2-column matrix).

like image 786
Fedja Blagojevic Avatar asked Nov 08 '11 13:11

Fedja Blagojevic


1 Answers

Well, there's a built-in combn function:

t(combn(vec1,2))

Yours looks faster, though, perhaps because combn is trying to solve a more general problem (??):

> library(rbenchmark)
> v <- 1:20
> benchmark(combi(v),t(combn(v,2)))
            test replications elapsed relative user.self sys.self
1       combi(v)          100   0.005      1.0     0.004    0.000   
2 t(combn(v, 2))          100   0.044      8.8     0.040    0.004   
like image 189
Ben Bolker Avatar answered Oct 01 '22 20:10

Ben Bolker