【发布时间】:2019-04-23 17:06:35
【问题描述】:
我有一个大小为 (r x c) 的矩阵 H,我想对该矩阵进行 100 次子采样,提取 100 个大小为 (m x c) 的矩阵,并将它们中的每一个存储到一个暗淡 (m x c x 100) 的数组中。
为了随机抽取子样本,我决定:
- 提取一百个长度为 m 的向量,其中包含随机 序列中的数字 (1:r)
- 将它们存储到大小为 (m x 100) 的矩阵中
- 使用该矩阵的每个向量作为标识符,从原始矩阵 H 中抽取 100 个矩阵
- 最后,将该子样本得到的每个矩阵存储到一个数组中,数组的第三维为100。
H = matrix( , nrow=r, ncol=c)
id = seq(1:r)
N_samples = 100
# Empty array and matrix of the random numbers
B = array( , c(m, c, N_samples))
h_sample = matrix( , nrow = m, ncol = N_samples)
# Extract random numbers from the sequence "id" without replacement
for(i in 1:N_samples){
h_sample[,i] = sample(id, m, replace = F)
}
## Now I sample the rows from H according to the identifiers randomly extracted and stored in matrix h_sample, and place each submatrix into the B array
for(j in 1:N_samples){
B[ , , j] = H[h_sample[ ,j], ]
}
它返回给我这个错误:
Error in B[, , i] = H[h_sample[, i], ] : incorrect number of subscripts
我知道问题出在代码的最后一行,你对处理这个错误有什么建议吗?您会建议解决此练习的其他方法吗?
【问题讨论】: