Sue
Sue

Reputation: 189

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. By repeating this process S=1000 times, I am interested find the upper 95% quantile of f2. 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. 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)

Upvotes: 0

Views: 202

Answers (1)

A. Webb
A. Webb

Reputation: 26466

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)

Upvotes: 2

Related Questions