快速函数,用于在R中以矩阵形式生成引导程序样本 [英] fast function for generating bootstrap samples in matrix forms in R
问题描述
我有一个矩阵A
,我想从A
的每一列中抽取样本并构造新的矩阵.例如:
I have a matrix A
, and I would like to draw samples from each column of A
and construct new matrices. For example:
A = matrix(seq(1,9),3,3)
因此要获得第一个引导矩阵,我将从A
的第一列进行替换(3次)采样,即1,2,3,从A
的第三列(即7,8,9)中进行替换(3次)采样.之后,我通过组合三个引导程序向量来重构第一引导程序矩阵B1.我将重复此过程B = 199次,以便可以使用引导矩阵B1,...,B199.
so to get the 1st bootstrap matrix, I would sample with replacement (3 times) from the first column of A
, i.e. 1,2,3, sample with replacement (3 times) from the second column of A
, i.e. 4,5,6, and sample with replacement (3 times) from the third column of A
, i.e. 7,8,9. After that, I re-construct the 1st bootstrap matrix B1 by combining the three bootstrap vectors. I will repeat this procedure for B=199 times, so that bootstrap matrices B1,...,B199 will be available.
我的问题是,如何使该程序运行更快?我应该使用哪个功能?我知道apply
本质上涉及for
循环,因此不能保证速度. do.call
怎么样?谢谢!
My question is, how can I make this program run faster? Which function should I use? I know apply
involves essentially for
loops so the speed is not guaranteed. How about do.call
? Thanks!
推荐答案
您可以使用replicate
和apply
:
A <- matrix(seq(1,9),3,3)
B <- 199
replicate(B, apply(A, 2, sample, replace = TRUE))
这篇关于快速函数,用于在R中以矩阵形式生成引导程序样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!