R 中的元素绑定
我想要一个函数 f
,使得
(outer(X, Y, f))[i, j]
是第 i 个元素的并排串联X 和 Y 的第 j 个元素,类似于 c(X[i], Y[j]) 或具有类似的结构。
此外,我希望这个结果能够重复该过程,这样我们就可以得到
(outer(outer(X, Y, f), Z, f))[i, j, k ]
是 X 的第 i 个元素、Y 的第 j 个元素和 Z 的第 k 个元素的并排串联,即相等或具有类似的结构其中,c(X[i], Y[j], Z[k])
。
最终我的目标是定义一个这样的函数:
foo <- function(a.list) {
Reduce(function(x, y) outer(x, y, f), a.list)
}
这样,如果
A <- foo(list(v_1, ..., v_p))
dim(A)
将是 c(length(v_1), ..., length(v_p))
code>,以及
A[i_1, ..., i_p] == c(v_1[i_1], ..., v_p[i_p])
所有有效索引集 (i_1, ..., i_p)。
例如:(
> 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")
注意:我不知道像上面示例中所示的结果这样的向量数组在 R 中是否有效/可能,但我使用像 c( "A", 3, "f")
来建议'一些类似向量的对象,其元素是 "A", 3, 和 "f"'。)
我可以用 f 来实现这个目的吗?
谢谢!
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"'.)
What can I use for f to achieve this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
函数
Vectorize()
是您的朋友:将f
定义为:上面对
foo
的定义):然后您可以执行以下操作(使用 例如,您可以检查条目是否与上面的示例匹配:
The function
Vectorize()
is your friend here: definef
to be:Then you can do (with your definition of
foo
above):For example you can check that the entries match your example above: