HeinKK
HeinKK

Reputation: 75

How can I fill a matrix with a repeat loop and delete columns by condition in R?

My R-Code:

l <- list() 

for(i in 1:5){
  n <- 1
mat <- matrix(0L,500,10)
  repeat{
  
  a <- rnorm(10)
  b <- rnorm(10) 
  
  c <- a+b 
  mat[n,] <- c 
  mat <- mat[mat[,10] >= 0 + (i/10) & mat[,1] >= 0 +(i/10),]
  n <- n +1 
  if(mat[500,] != 0){
    break 
  }
}
l[[i]] <- mat 
}
l

I would like to get 5 Matrices, which are stored in a list. Each matrix should have exactly 500 rows and should not have negative values in its rows at position [,1] or [,10]. I tried to build a repeat loop:

  1. Calculate Vector
  2. Store vector in matrix
  3. delete if condition is met
  4. repeat if there arent 500 rows

Unfortunately, there's something wrong and it doesn't work. What can I do? Thanks!

Upvotes: 1

Views: 213

Answers (1)

Max Teflon
Max Teflon

Reputation: 1800

If you add an if-clause that tests your condition before adding the line to your matrix, it should work:

l <- list() 

for(i in 1:5){
  n <- 1
  mat <- matrix(0L,500,10)
  repeat{
    
    a <- rnorm(10)
    b <- rnorm(10) 
    
    c <- a+b 
    if(!any(c[c(1,10)] < 0 + i/10)){
      mat[n,] <- c 
      n <- n +1 
    }
    if(n==501){
      break 
    }
  }
  l[[i]] <- mat 
}

Upvotes: 2

Related Questions