【问题标题】:Multiple Matrix subset and store in Array多个矩阵子集并存储在数组中
【发布时间】:2019-04-23 17:06:35
【问题描述】:

我有一个大小为 (r x c) 的矩阵 H,我想对该矩阵进行 100 次子采样,提取 100 个大小为 (m x c) 的矩阵,并将它们中的每一个存储到一个暗淡 (m x c x 100) 的数组中。

为了随机抽取子样本,我决定:

  1. 提取一百个长度为 m 的向量,其中包含随机 序列中的数字 (1:r)
  2. 将它们存储到大小为 (m x 100) 的矩阵中
  3. 使用该矩阵的每个向量作为标识符,从原始矩阵 H 中抽取 100 个矩阵
  4. 最后,将该子样本得到的每个矩阵存储到一个数组中,数组的第三维为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

我知道问题出在代码的最后一行,你对处理这个错误有什么建议吗?您会建议解决此练习的其他方法吗?

【问题讨论】:

    标签: arrays r subset


    【解决方案1】:

    解决此问题的一种方法是使用基本函数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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多