Question

 SimNo <- 10

 for (i in 1:SimNo){
  z1<-rnorm(1000,0,1)
  z2<-rnorm(1000,0,1)
  z3<-rnorm(1000,0,1)
  z4<-rnorm(1000,0,1)
  z5<-rnorm(1000,0,1)
  z6<-rnorm(1000,0,1)

  X<-cbind(z1,z2,z3,z4,z5,z6)
  sx<-scale(X)/sqrt(999)
  det1<-det(t(sx)%*%sx)
  detans<-do.call(rbind,lapply(1:SimNo, function(x) ifelse(det1<1,det1,0)))
 }

when I run all commands with in loop except last one I get different values of determinant but when I run code with loops at once I get last value of determinant repeated for all.

Please help and guide to control all situation like this.

Is there way to have short and efficient way for this code, so that each individual variable can also be accessed.

Was it helpful?

Solution

Whenever you are repeating the same operation multiple times, and without inputs, think about using replicate. Here you can use it twice:

SimNo <- 10

det1 <- replicate(SimNo, { 
   X  <- replicate(6, rnorm(1000, 0, 1))
   sx <- scale(X) / sqrt(999)
   det(t(sx) %*% sx)
})

detans <- ifelse(det1 < 1, det1, 0)

Otherwise, this is what your code should have looked with your for loop. You needed to create a vector for storing your outputs at each loop iteration:

SimNo <- 10
detans <- numeric(SimNo)
for (i in 1:SimNo) {
  z1<-rnorm(1000,0,1)
  z2<-rnorm(1000,0,1)
  z3<-rnorm(1000,0,1)
  z4<-rnorm(1000,0,1)
  z5<-rnorm(1000,0,1)
  z6<-rnorm(1000,0,1)

  X<-cbind(z1,z2,z3,z4,z5,z6)
  sx<-scale(X)/sqrt(999)
  det1<-det(t(sx)%*%sx)
  detans[i] <- ifelse(det1<1,det1,0)
}

Edit: you asked in the comments how to access X using replicate. You would have to make replicate create and store all your X matrices in a list. Then use the *apply family of functions to loop throughout that list to finish the computations:

X <- replicate(SimNo, replicate(6, rnorm(1000, 0, 1)), simplify = FALSE)

det1 <- sapply(X, function(x) {
  sx <- scale(x) / sqrt(999)
  det(t(sx) %*% sx)
})

detans <- ifelse(det1 < 1, det1, 0)

Here, X is now a list of matrices, so you can get e.g. the matrix for the second simulation by doing X[[2]].

OTHER TIPS

SimNo <- 10
matdet <- matrix(data=NA, nrow=SimNo, ncol=1, byrow=TRUE)

for (i in 1:SimNo){
  z1<-rnorm(1000,0,1)
  z2<-rnorm(1000,0,1)
  z3<-rnorm(1000,0,1)
  z4<-rnorm(1000,0,1)
  z5<-rnorm(1000,0,1)
  z6<-rnorm(1000,0,1)

  X<-cbind(z1,z2,z3,z4,z5,z6)
  sx<-scale(X)/sqrt(999)
  det1<-det(t(sx)%*%sx)

 matdet[i] <-do.call(rbind,lapply(1:SimNo, function(x) ifelse(det1<1,det1,0)))
}
matdet
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top