从没有循环的另一个矩阵的随机块行创建矩阵(在R中)?

时间:2014-09-18 00:23:45

标签: r random matrix block rows

我试图通过从另一个矩阵中绘制随机块行来创建矩阵。我已经成功完成了循环。

set.seed(1)
a_matrix  <- matrix(1:10,10,5) # the matrix with original sample 

b_matrix <- matrix(NA,10, 5) # a matrix to store the bootstrap sample 

S2<- seq(from =1 , to = 10, by =2) #[1] 1 3 5 7 9

m <- 2 # block size of m 

for (r in S2){  start_point<-sample(1:(nrow(a_matrix)-1), 1, replace=T) 
                #randomly choose a number 1 to length of a_matrix -1  
                b_block <- a_matrix[start_point:(start_point+(m-1)), 1:ncol(a_matrix)] 
                # randomly select blocks  from matrix a 
                b_matrix[r,]<-as.matrix((b_block)[1,]) 
                b_matrix[(r+1),]<-as.matrix((b_block)[2,]) # put the blocks into matrix b 
} 
b_matrix
#we now have a b_matrix that is made of random blocks (size m=2)
#of the original a_matrix  

循环方法有效,但显然效率不高,无法将其扩展到其他块大小(例如,块大小为3)。什么是更清洁和可扩展的方法?提前致谢

1 个答案:

答案 0 :(得分:1)

在这里,我尝试将其清理一下并概括使用m

random_block_sample <- function(a_matrix, m = 2L) {
   N <- nrow(a_matrix)
   stopifnot(m <= N)
   n <- ceiling(N / m)
   s <- sample(N - m + 1L, n, TRUE) # start_point
   i <- unlist(lapply(s, seq, length.out = m))
   b_matrix <- a_matrix[i, , drop = FALSE]
   head(b_matrix, N)
}

set.seed(1L)
random_block_sample(a_matrix, m = 2L)
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    3    3    3    3    3
#  [2,]    4    4    4    4    4
#  [3,]    4    4    4    4    4
#  [4,]    5    5    5    5    5
#  [5,]    6    6    6    6    6
#  [6,]    7    7    7    7    7
#  [7,]    9    9    9    9    9
#  [8,]   10   10   10   10   10
#  [9,]    2    2    2    2    2
# [10,]    3    3    3    3    3

set.seed(1L)
random_block_sample(a_matrix, m = 5L)
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    2    2    2    2    2
#  [2,]    3    3    3    3    3
#  [3,]    4    4    4    4    4
#  [4,]    5    5    5    5    5
#  [5,]    6    6    6    6    6
#  [6,]    3    3    3    3    3
#  [7,]    4    4    4    4    4
#  [8,]    5    5    5    5    5
#  [9,]    6    6    6    6    6
# [10,]    7    7    7    7    7