Elemental binding in R

I need a function f such that

(outer(X, Y, f))[i, j] is a side-by-side concatenation of the ith element of X and the jth element of Y, something like c(X[i], Y[j]) or having a similar structure.

In addition, I want this result to be such that the process can be repeated, and so we get that

(outer(outer(X, Y, f), Z, f))[i, j, k] is side by side concatenation of the i-th element of X, the j-th element of Y and the k-th element of Z, i.e. . something equal to or having a structure similar to, c(X[i], Y[j], Z[k]) .

I end up trying to define a function like this:

 foo <- function(a.list) { Reduce(function(x, y) outer(x, y, f), a.list) } 

such that if

 A <- foo(list(v_1, ..., v_p)) 

then dim(A) will be c(length(v_1), ..., length(v_p)) , and

 A[i_1, ..., i_p] == c(v_1[i_1], ..., v_p[i_p]) 

for all valid index sets (i_1, ..., i_p).

For instance:

 > foo(list(LETTERS[1:2], c(3, 4, 5), letters[6:7])) , , 1 [,1] [,2] [,3] [1,] c("A", 3, "f") c("A", 4, "f") c("A", 5, "f") [2,] c("B", 3, "f") c("B", 4, "f") c("B", 5, "f") , , 2 [,1] [,2] [,3] [1,] c("A", 3, "g") c("A", 4, "g") c("A", 5, "g") [2,] c("B", 3, "g") c("B", 4, "g") c("B", 5, "g") 

( NOTE : I don't know if the array of vectors is similar to the result shown in the above example, even valid / possible in R, but I use expressions like c("A", 3, "f") to suggest 'some vector object whose elements are "A", 3 and "f" '.)

What can I use for f for this?

Thanks!

+4
source share
1 answer

The Vectorize() function is your friend here: define f for:

 f <- Vectorize( function(a,b) c(as.list(a), as.list(b)), SIMPLIFY = FALSE ) 

Then you can do (with your foo definition above):

 z <- foo(list(LETTERS[1:2], c(3, 4, 5), letters[6:7])) 

For example, you can verify that the entries match your example above:

 > z , , 1 [,1] [,2] [,3] [1,] List,3 List,3 List,3 [2,] List,3 List,3 List,3 , , 2 [,1] [,2] [,3] [1,] List,3 List,3 List,3 [2,] List,3 List,3 List,3 > z[2,2,2] [[1]] [[1]][[1]] [1] "B" [[1]][[2]] [1] 4 [[1]][[3]] [1] "g" 
+5
source

All Articles