gpt4 book ai didi

R 索引数组。如何使用第 3 维矩阵索引 3 维数组

转载 作者:行者123 更新时间:2023-12-04 10:33:13 24 4
gpt4 key购买 nike

我有一个关于索引 3 个暗数组的问题。

说我有一个 3 维数组

x<- c(1:36)
dim(x) <- c(3,4,3)

现在我想根据包含所有 [i,j] 位置的第 3 维索引的矩阵从该数组中提取值。
y <- c(rep(1,4),rep(2,4),rep(3,4))
dim(y) <- c(3,4)

y
[,1] [,2] [,3] [,4]
[1,] 1 1 2 3
[2,] 1 2 2 3
[3,] 1 2 3 3

所以结果应该是这样的:
     [,1] [,2] [,3] [,4]
[1,] 1 4 19 34
[2,] 2 17 20 35
[3,] 3 18 33 36

有没有一些优雅的方法来做到这一点?我知道如何使用两个 for 循环遍历数组,但这对我的数据来说太慢了。

最佳答案

help("[") 告诉我们:

Matrices and arrays

[...]

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.



因此,我们将您的 y 矩阵转换为与此相符的形状。
library(reshape2)
z <- x[as.matrix(melt(y))]
dim(z) <- dim(y)
# [,1] [,2] [,3] [,4]
#[1,] 1 4 19 34
#[2,] 2 17 20 35
#[3,] 3 18 33 36

关于R 索引数组。如何使用第 3 维矩阵索引 3 维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com