I want a function f
such that
(outer(X, Y, f))[i, j]
is a side-by-side concatenation of the i-th element of X and the j-th element of Y, something like c(X[i], Y[j])
, or having a similar structure.
Furthermore, I want this result to be such that the process can be repeated, and, in this way we get that
(outer(outer(X, Y, f), Z, f))[i, j, k]
is a 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, or having a structure similar to that of, c(X[i], Y[j], Z[k])
.
Ultimately I am aiming for defining 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 example:
> 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 an array of vectors like the result shown in the example above is even valid/possible in R, but I am using expressions like c("A", 3, "f")
to suggest 'some vector-like object whose elements are "A", 3, and "f"'.)
Wh开发者_C百科at can I use for f to achieve this?
Thanks!
The function Vectorize()
is your friend here: define f
to be:
f <- Vectorize( function(a,b) c(as.list(a), as.list(b)), SIMPLIFY = FALSE )
Then you can do (with your definition of foo
above):
z <- foo(list(LETTERS[1:2], c(3, 4, 5), letters[6:7]))
For example you can check 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"
精彩评论