More generalized expand.grid function?

expand.grid (a, b, c) produces all combinations of values ​​in a, b and c in the matrix - essentially filling the volume of the three-dimensional cube. What I want is a way to get slices or lines from this cube (or a higher dimensional structure) centered on the cube.

So, given that a, b, c are all vectors of odd length (therefore, they have a center), and in this case let them say that they are of length 5. My hypothetical function slice.grid:

slice.grid(a,b,c,dimension=1) 

returns the matrix of coordinates of points along three center lines. Almost equivalent:

 rbind(expand.grid(a[3],b,c[3]), expand.grid(a,b[3],c[3]), expand.grid(a[3],b[3],c)) 

almost because it has a central point repeated three times. Besides:

 slice.grid(a,b,c,dimension=2) 

should return a matrix equivalent to:

 rbind(expand.grid(a,b,c[3]), expand.grid(a,b[3],c), expand.grid(a[3],b,c)) 

which are three intersecting planes aligned along the axis (with repeating points in the matrix at the intersections).

And then:

 slice.grid(a,b,c,dimension=3) 

matches expand.grid (a, b, c).

This is not so bad with three parameters, but ideally I would like to do this using N parameters passed to the expand.grid function (a, b, c, d, e, f, dimension = 4) - I’m unlikely to Or would like a size larger than 3.

This can be done by executing the .grid extension and then extracting the points that are required, but I'm not sure how to build this criterion. And I always get the feeling that this function exists in some package somewhere ...

[Edit] That's right, I think that now I have a criterion that can be determined how many times the central value appears in each row. If it is smaller or equal to your size + 1 ...

But the generation of the full matrix is ​​increasing rapidly. It will be done now.

+4
source share
1 answer

Assuming a , b and c are 3 in length (and if there are 4 variables, then each of them has 4 lengths, etc.) try this. It works using 1: 3 instead of each of a , b and c , and then counts how many 3 are in each row. If there are four variables, then it uses 1: 4 and calculates how many 4 are in each row, etc. He uses this for an index to select the appropriate rows from expand.grid(a, b, c) :

 slice.expand <- function(..., dimension = 1) { L <- lapply(list(...), seq_along) n <- length(L) ix <- rowSums(do.call(expand.grid, L) == n) >= (n-dimension) expand.grid(...)[ix, ] } # test a <- b <- c <- LETTERS[1:3] slice.expand(a, b, c, dimension = 1) slice.expand(a, b, c, dimension = 2) slice.expand(a, b, c, dimension = 3) 
+1
source

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


All Articles