Spartan 117
Spartan 117

Reputation: 129

How to find unique couples of numbers in a vector in R?

Let us suppose to have C<-c(1,2,3,4,5) I want to find all the unique couples of numbers that can be extracted from this vector, e.g.,12,13 23 etc. How can I do it?

Upvotes: 1

Views: 170

Answers (2)

jay.sf
jay.sf

Reputation: 72673

Using RcppAlgos package.

## Combinations
unlist(RcppAlgos::comboGeneral(x, 2, FUN=function(x) Reduce(paste0, x)))
# [1] "12" "13" "14" "15" "23" "24" "25" "34" "35" "45"

## Permutations
unlist(RcppAlgos::permuteGeneral(x, 2, FUN=function(x) Reduce(paste0, x)))
# [1] "12" "13" "14" "15" "21" "23" "24" "25" "31" "32" "34" "35" "41" "42" "43"
# [16] "45" "51" "52" "53" "54"

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

One option could be:

na.omit(c(`diag<-`(sapply(x, paste0, x), NA)))

 [1] "12" "13" "14" "15" "21" "23" "24" "25" "31" "32" "34" "35" "41" "42" "43" "45"
[17] "51" "52" "53" "54"

Upvotes: 1

Related Questions