【发布时间】:2014-09-18 00:23:44
【问题描述】:
我正在尝试通过从另一个矩阵中绘制随机块行来创建一个矩阵。我已经设法通过循环来做到这一点。
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)。什么是更清洁和可扩展的方法?在此先感谢
【问题讨论】:
-
这个问题更符合Code Review
标签: r random matrix block rows