R: conditional function expand.grid

I would like to find all combinations of vector elements that match a specific condition. The expand.grid function returns all possible combinations without checking for a specific state. You can verify a specific condition after using the expand.grid function, but in some situations the number of possible combinations is too large to generate them using expand.grid. Therefore, there is a function that allows me to check the condition when creating all possible combinations.

This is a simplified version of the problem:

A <- seq.int(12, from=0, by=1)*15 B <- seq.int(27, from=0, by=1)*23 C <- seq.int(18, from=0, by=1)*18 D <- seq.int(33, from=0, by=1)*10 out<-expand.grid(A,B,C,D) #out is a dataframe with 235144 x 4 as dimensions idx<-which(rowSums(out)<=400 & rowSums(out)>=300) #Only a small fraction of 'out' is needed results <- out(idx,) 
+6
source share
1 answer

In a word, no. After all, if you knew a priori which combinations were desirable / unwanted, you could exclude them from the extension, for example. expand.grid(A[A<20],B[B<15],...) . In the general case, which I assume is your real question, you have no easy way to exclude parts of the input vectors.

You can simply write a multi-level loop that checks each combination one at a time and saves or rejects it. This will be slow (again, unless you come up with some clever algorithm for predicting regions that are all TRUE or FALSE). Thus, in the end, it may be useful for you to use some of the R packages that break up large computations (and data sets) so as not to exceed your memory limits.

Now that I have said all this, someone will send a link to a package that does just that: - (

+1
source

Source: https://habr.com/ru/post/953689/


All Articles