I need to find the SUM of all possible combinations in a set. For example:
sum(choose(5, 0),
choose(5, 1),
choose(5, 2),
choose(5, 3),
choose(5, 4),
choose(5, 5))
Instead of writing it out like that, is possible to use a for loop to loop through choose()
with any given n
and k
?
CodePudding user response:
In case you want to do this for more than just one n
you can use sapply
setNames( sapply( 1:10, function(x) sum( choose( x, 0:x ) ) ), 1:10 )
1 2 3 4 5 6 7 8 9 10
2 4 8 16 32 64 128 256 512 1024
Or using a for
loop
res <- vector(l=10)
for(i in 1:10){ res[i] <- sum( choose( i, 0:i ) ) }
res
[1] 2 4 8 16 32 64 128 256 512 1024
CodePudding user response:
You can use
> sum(choose(5, 0:5))
[1] 32
or just apply the binomial sums
> 2^5
[1] 32