Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce combinations iteratively in R? [duplicate]

So I am currently using the following code to generate my combinations:

combn(x,y)

But the thing is that function stores all of the possible combinations. I dont want to store them, I just want to produce them through like a loop or something. It would be way more efficient for my program. Is there a way to generate combinations through a for loop rather than storing them all?

I know I asked a similar question here: How do I find all possible subsets of a set iteratively in R?

But in that solution the combinations are still being stored...

Here is some more detail:

Lets say I want to find 4 choose 2. combn(4,2) would essentially store the following: ((1,4),(1,3),(1,2),(2,4),(2,3)(3,4))

What I want is this:

   loop{
       produces one combination at a time 
   }
like image 623
user2560984 Avatar asked Oct 28 '25 05:10

user2560984


1 Answers

To return each of the possible combinations, one at a time, in a loop, do the following:

#Sample data:
x <- c(1,2,3,4)
y <- 2
all_combinations <- combn(x,y)

#Return each value:
for (i in 1:ncol(all_combinations)) {
  print(all_combinations[,i])
}

But I'm not sure why you want to do this in a for loop, given that it's pretty slow. Is there a desired final output beyond this application?

like image 143
canary_in_the_data_mine Avatar answered Oct 29 '25 19:10

canary_in_the_data_mine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!