2
\$\begingroup\$

I have this custom function to show the combinations:

x<-function(a,b){

  ncol(combn(a,b))

}

combinations<-numeric()

for(i in 0:12){
    combinations<-c(combinations,x(12,i))
}

combinations

It works, but I want to know if it's possible to do something simpler, like this:

x<-function(a,b){

  ncol(combn(a,b))

}

x(12,0:12)
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

The number of combinations of size k from a set of size n can be computed with choose(n, k) in R, and if you have multiple k values you can just pass in a vector for k. Therefore your code can be simplified to:

choose(12, 0:12)
#  [1]   1  12  66 220 495 792 924 792 495 220  66  12   1
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.