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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With