Manuel K
Manuel K

Reputation: 67

How to fill out a matrix with a loop in R?

a <- function(b,c,d,e,f){ 
if(f == 1){
  Value1 <- b * c * d * e
  return(Value1)
}else if(f == 2){
  Value2 <- b * c * d
  return(Value2) 
}else{
  Value3 <- 0 
}
}

Assume i would like to analyze the relationship between Value2 and d for d =seq(1,1.2,0.01) with c = seq(1,2,0.2) and b,e,f are fixed.

I tried this:

ValueChange <- matrix(,6,21) 

for(i in seq(1,1.2,0.01)){
  for(j in seq(1,2,0.2)){
    for(n in 1:6){

      ValueChange[n,] <- c(ValueChange, a(10,j,i,5,2))

    }
}
}
ValueChange

It should be like this:

ValueChange[1,1] <- a(10,1,1,5,2)
ValueChange[1,2] <- a(10,1,1.01,5,2)
... 
ValueChange[2,1] <- a(10,1.2,1,5,2)
...

There is an error message: number of items to replace is not a multiple of replacement length. However, I have no idea how to fix it. Thanks for your help!

Upvotes: 0

Views: 50

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101099

For your nested for loop, it might be something like

p <- seq(1,1.2,0.01)
q <- seq(1,2,0.2)
for(i in seq_along(p)){
  for(j in seq_along(q)){
      ValueChange[j,i] <- a(10,q[j],p[i],5,2)
  }
}

Maybe you can try nested sapply

ValueChange <- sapply(seq(1,1.2,0.01), function(i) sapply(seq(1,2,0.2), function(j) a(10,j,i,5,2)))

which gives the same result as nested for loop

Upvotes: 1

Related Questions