简体   繁体   English

在R中,避免循环或套用或套用

[英]In R, avoid for loop or apply or lapply

In the following code, for matrix Ma, the standard normal random vector x1 is multiplied and the column sums and maximum are obtained. 在以下代码中,对于矩阵Ma,将标准法向随机向量x1相乘,并获得列总和和最大值。 By repeating this process S=1000 times, I am interested find the upper 95% quantile of f2. 通过重复此过程S = 1000次,我很感兴趣地找到f2的高95%分位数。 Due to the high dimensional matrices, it took a lot of and when I tried lapply with some modifications, I got an error message about memory allocation. 由于高维矩阵,它花费了很多时间,当我尝试对Lapply进行一些修改时,我收到了有关内存分配的错误消息。 Is there anyway to make this simulation faster? 无论如何,可以使此模拟更快吗? Thanks in advance. 提前致谢。

set.seed(1)
S=1000; n=1000; D=10000

Ma=matrix(rnorm(n*D),ncol=D)
f2<-NULL

for (i in 1:S){
x1=rnorm(n,0,1)
f1=colSums(Ma*x1)
f2[i]=max(f1)
}

q=quantile(f2,0.95)

This question is just a minor variation of your previous question. 这个问题只是您先前问题的一个细微变化。 The following is equivalent. 以下是等效的。

set.seed(1)
S <- n <- 1000
D <- 10000

Ma <- matrix(rnorm(n*D),ncol=D)
x1 <- matrix(rnorm(n*S,0,1),ncol=S)
f1 <- crossprod(Ma,x1)
f2 <- apply(f1,2,max)
q <- quantile(f2,0.95)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM