我在数组的索引上复制矩阵时遇到了麻烦.下面是我问题的简化版本.我不明白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的回收规则有关如果在初始化后查看test_array,您会看到以下输出:

test_array <- array(NA, c(4,3,2))
test_matrix <- t(matrix(1:2, nrow = 2, ncol = 4))

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
#      [,1] [,2]
# [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 3 2
dim(test_array[, 1, , drop = FALSE])
# [1] 4 1 2

总的来说,在赋值的情况下,如果使用多个列,R需要进行一些循环来拟合维度,而对于单个列,维度匹配,不需要循环.


为了解决这个问题,你需要复制你的测试矩阵来考虑最后一个维度:

r <- rep(test_matrix, each = 3)
dim(r) <- dim(test_array)

test_array[, 1:3, ] <- r
test_array
# , , 1
# 
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    1    1    1
# [3,]    1    1    1
# [4,]    1    1    1
# 
# , , 2
# 
#      [,1] [,2] [,3]
# [1,]    2    2    2
# [2,]    2    2    2
# [3,]    2    2    2
# [4,]    2    2    2

R相关问答推荐

带有gplot 2的十字舱口

以R中的正确顺序将日期时间字符列转换为posixct

使用ggsankey调整Sankey图中单个 node 上的标签

自动变更列表

将文件保存到新文件夹时,切换r设置以不必创建目录

使用`Watch()`和`renderUI()`时,不再满足仍出现在SHILINY AFTER条件中的条件输入

过滤名称以特定字符串开头的文件

以字符格式导入的ExcelElectron 表格日期列标题

以NA为通配符的R中的FULL_JOIN以匹配其他数据中的任何值.Frame

如何对r中包含特定(未知)文本的行求和?

在R中使用列表(作为tibble列)进行向量化?

为什么我对圆周率图的蒙特卡罗估计是空的?

有没有办法定制Plot(allEffects())面板标题?

有没有办法将基于每个值中出现的两个关键字或短语的字符串向量重新编码为具有这两个值的新向量?

在ggploy中创建GeV分布时出错

整理曲线图、曲线图和点图

如何在AER::ivreg中指定仪器?

我已经运行了几个月的代码的`Palette()`中出现了新的gglot错误

位置_道奇在geom_point图中不躲避

Ggplot2水平线和垂直线的图例图标不匹配