在数组的索引上复制矩阵时出现问题

问题描述 投票:0回答:1

我在通过数组的索引复制矩阵时遇到问题。这是我的问题的简化版本。我不明白R在这里做什么...

test_array <- array(NA, c(4,3,2))
test_matrix <- as.matrix(data.frame(rep(1, 4),rep(2, 4)))
test_array[,1:3,] <- test_matrix  # I want this matrix duplicated across this array such that the below commands print the exact same result: the test_matrix
test_array[,1,]
test_array[,2,] # What's going on here?
test_array[,3,]

我错过了什么?如果上面的方法不起作用,那么为什么下面的方法可以正常工作?

test_array <- array(NA, c(4,3,3))
test_matrix <- as.matrix(data.frame(rep(1, 4),rep(2, 4),rep(3, 4)))
test_array[,,1:3] <- test_matrix
test_array[,,1]
test_array[,,2]
test_array[,,3]

这也很好用,但我真的不想循环它:

test_array <- array(NA, c(4,3,2))
test_matrix <- as.matrix(data.frame(rep(1, 4),rep(2, 4)))
test_array[,1,] <- test_matrix
test_array[,2,] <- test_matrix
test_array[,3,] <- test_matrix
test_array[,1,]
test_array[,2,]
test_array[,3,]

干杯

r arrays multidimensional-array
1个回答
0
投票

嗯,这与 R 的回收规则有关。如果您在初始化后查看

test_array
,您会看到以下输出:

test_array
# , , 1
# 
#      [,1] [,2] [,3]
# [1,]   NA   NA   NA
# [2,]   NA   NA   NA
# [3,]   NA   NA   NA
# [4,]   NA   NA   NA
# 
# , , 2
# 
#      [,1] [,2] [,3]
# [1,]   NA   NA   NA
# [2,]   NA   NA   NA
# [3,]   NA   NA   NA
# [4,]   NA   NA   NA

现在你的

test_matrix
看起来像这样:

test_matrix

#      rep.1..4. rep.2..4.
# [1,]         1         2
# [2,]         1         2
# [3,]         1         2
# [4,]         1         2

现在,如果您想将其存储到

test_array[, 1:3, ]
中(顺便说一下,与
test_array
相同),R 会复制矩阵以使其适合维度。也就是说,每个奇数列将是填充 1 的列,每个偶数列将填充 2(如果这有助于理解,则第二个矩阵的第一列可以视为整体的第四列)。

也就是说,如果您要求

test_array{, 1, ]
,您将获得每个矩阵的第一列。

现在为什么使用单个索引就可以工作呢?如果可能的话,这是 b/c R 默默地删除维度,除非您指定

drop = FALSE
:

dim(test_array[,1,])
# [1] 4 2
dim(test_array[,1:3,])
# [1] 4 2 2
dim(test_array[,1,,drop = FALSE])
# [1] 4 1 2

总体而言,在分配情况下,如果使用多个列,R 需要进行一些回收以适应维度,而对于单个列,维度适合并且不需要回收。

© www.soinside.com 2019 - 2024. All rights reserved.