我有一个大小为(r x c)的矩阵H,我想对该矩阵进行100次子采样,以提取100个大小为(m x c)的矩阵,并将每个矩阵存储到一个昏暗的数组(m x c x 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
我知道问题出在代码的最后一行,您是否有一些建议来解决此错误?您是否会提出解决此问题的替代方法?
答案 0 :(得分:0)
一种解决方法是使用基本函数replicate
,在这种情况下,该函数将复制设置了指定次数的子集并直接创建矩阵数组。
r <- 100 # number of rows
c <- 50 # number of columns
m <- 10 # number of rows you want to extract
# example matrix
H = matrix(rnorm(r*c), nrow=r, ncol=c)
arr <- replicate(100, {
id <- sample(1:r,m, replace = FALSE) # if you want to sample rows without replacement
H[id,]
})
dim(arr)
# [1] 10 50 100