将向量转换为R中的数组索引? [英] Convert vector to array index in R?
问题描述
假设我们有一个数组A,它具有任意维dim(A).假设我们有一个坐标索引向量V.是否可以通过坐标V访问A的元素?像A [V]这样的事情显然是行不通的.如果V = c(1,2,3),那么A [V]只会给我们A的第1,第2和第3个元素.如果我们想要A [1,2,3]怎么办?如果我们提前知道dim(A),显然这很容易.但是,如果我们要使代码无论A有多少维都可以工作,该怎么办?
Say that we have an array A, that has arbitrary dimension dim(A). Say that we have a coordinate index vector V. Is there any way to access the element of A with coordinates V? Doing something like A[V] doesn't work obviously. If V=c(1,2,3) then A[V] will just give us the 1st, 2nd, and 3rd element of A. What if we want A[1,2,3] instead? If we know dim(A) ahead of time, this is easy obviously. But what if we want to make code that works no matter how many dimensions A has?
推荐答案
我们可以使用 do.call
执行`[`
.
v <- c(1, 2, 3)
do.call(`[`, c(list(A), v))
# [1] 22
要分配,我们有`[< -`
.
A <- do.call(`[<-`, c(list(A), v, 99))
检查:
A[,,3]
# , , 3
#
# [,1] [,2] [,3]
# [1,] 19 99 25
# [2,] 20 23 26
# [3,] 21 24 27
使用 @duckmayr的 A
A <- array(1:(3^3), dim = c(3, 3, 3))
这篇关于将向量转换为R中的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!