Create code for n choose k

I want to create a code for n choose k.
Such that for I am able to get the subsets k.
n=3, k=2


A_2= a1a2, a2a3, a1a3
and add a count function to count all the subsets

What have you tried so far? If you haven't tried anything yet, do you have any hunches where to start?


The following creates a matrix where each column is one size k combination.

n <- 3
k <- 2
combn(paste0("a", 1:n), k)

I have not started yet. i want
eg, n=3, k=2
subsets = (1,2),(1,3),(2,3)
and these subsets should also get counted

I think what people are looking for is to you to come up with some code, illustrating how you have tried to solve the problem. The reason for this is that people want you to learn to solve the problem, not solve the problem for you :slightly_smiling_face:

So, start with a suggestion on how this problem might be solved and then I'm sure that people will be more than happy to engage in a discussion leading you on the 'learning-path':

# Insert your code here :-)


I am getting answer as 1 2 3. I want the answers as sets of (1,2), (2,3), (1,3)

@goldbiggod, your example creates a vector n, with elements 1, 2 and 3, then you ask for elements larger than zero, which is all of them.

You have still to show us some code, which shows us, that you have put in a effort to solve the challenge. If you just want it to work, you can do this:

combn(1:3, 2)
#      [,1] [,2] [,3]
# [1,]    1    1    2
# [2,]    2    3    3

and then if you want

apply(combn(1:3, 2),2,function(x){ return( paste0('(',x[1],',',x[2],')') ) })
# [1] "(1,2)" "(1,3)" "(2,3)"
1 Like