Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

loops - How do I find all possible subsets of a set iteratively in R?

So I know that the following command would store all possible combinations of a desired length y in a list, where y < j:

 lapply(y, function(x) combn(j,x))

But I don't want them all to be stored in a list because later on I will be accessing them only once so it's not efficient to store them in memory. Is there a way where I can just produce each combination in some sort of a loop or something, and then after I'm done performing a calculation, it would just give me the next combination? So basically I want to produce the combinations iteratively instead of storing them first.

So in pseudo code, what i'd like to have is:

#loop that will generate each possible combination one by one
loop{
  operation that uses combination
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No need for loops (lapply or otherwise):

combn(1:4,2)
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    1    1    2    2    3
# [2,]    2    3    4    3    4    4

Example with calculating the sums of combinations:

combn(1:4,2,FUN=sum)
# [1] 3 4 5 5 6 7

An example with a user defined function:

x <- 11:14
combn(1:4,2,FUN=function(i,a) sum(a[i]),a=x)
#[1] 23 24 25 25 26 27

Here (in the anonymous function) i is the combination used as index and argument a is a vector to which I pass x.

And the same with a user-defined named function:

fun <- function(i,a) sum(a[i])
combn(1:4,2,FUN=fun,a=x)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...