简体   繁体   中英

Optimizing an R code with For Loop with matrix

I need to convert the following code to one with for loop, what is the easiest way to do it?

set.seed(123)
iter <- 1000
s1 <- 2
mat1 <- matrix(data = rcauchy(iter*s1,0,1),nrow = iter,ncol = s1)
sets1 <- apply(mat1,1,median)
hist(sets1)

s2 <- 5
mat2 <- matrix(data = rcauchy(iter*s2,0,1),nrow = iter,ncol = s2)
sets2 <- apply(mat2,1,median)
hist(sets2)

s3 <- 10
mat3 <- matrix(data = rcauchy(iter*s3,0,1),nrow = iter,ncol = s3)
sets3 <- apply(mat3,1,median)
hist(sets3)

s4 <-20
mat4 <- matrix(data = rcauchy(iter*s4,0,1),nrow = iter,ncol = s4)
sets4 <- apply(mat4,1,median)
hist(sets4)

I tried the following:

set.seed(1234)
iter <- 1000
size <- c(2,5,10,20)
for(i in 2:size){
  for (j in 1:iter){
     mat[] <- matrix(data = rcauchy(i*j,0,1),nrow=iter,ncol=i)
     s <- apply(mat,1,median)
     hist(s)
}
}

But it does not work, please help

The easies way is to wrap the creation of the matrix into a lapply function.

set.seed(123)
iter <- 1000
size <- c(2,5,10,20)

returnmatrix<-lapply(size, function(i){
  mat<-matrix(data = rcauchy(i*iter,0,1),nrow=iter,ncol=i)
  s <- apply(mat,1,median)
  hist(s, main=paste("Histogram when S=", i))
  mat
})

The lapply function will plot the histograms and will return the matrixes as list if additional processing is desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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