0

I am working on a loop in R:

dypol and wnc are 1-by-3 matrices and x is a 1-by-100 matrix. I want the loop to return a 3-by-100 matrix (cumulative for each column). I have this:

For (i in 1:100) {
i=dypol*t(x^2)-dypol+wnc
{yi = cumsum(i) }
}

but it returns only the first row.

flodel
  • 87,577
  • 21
  • 185
  • 223
Adam
  • 434
  • 1
  • 4
  • 18
  • If `dypol` is 1-by-3 and `x` is 1-by-100, then you cannot take `dypol * t(x^2)`. – flodel Oct 07 '12 at 12:30
  • @Adam - Good to see that you provided what code you have. For one thing you seem to be overwriting the loop counter i as you go through the loop. If you can supply the data in your question as well as the code it will be easier for people to help you. But even before that, it's not clear (at least to me) how you want your calculation to work, so it may be worth you attempting a clearer explanation. See this post for guidance on asking questions: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610 – SlowLearner Oct 07 '12 at 12:44
  • Ok, thanks for the tips. My data looks like this x= (0:100) wnc=(0.123 0.263 0.223) dypol=( .05 .30 .02) the results of the loop should look like this (just an example) x A B C 1 0,1232 0,2633 0,2230 2 0,1233 0,2634 0,2231 5 0,1244 0,2640 0,2237 .. 100 So, for the second row for A =0.05*t(1^2)-0.05+.123] + [0.05*t(2^2)-0.05+.123] – Adam Oct 07 '12 at 14:28
  • Good questions often come with a **small** reproducible example. You could for example have used an example where `x` has length `4` and shown exactly what the expected output should be. – flodel Oct 07 '12 at 15:02

1 Answers1

0

Try this. I have converted the loop into a sapply call (which effectively loops over x), then applied cumsum on the columns of the resulting matrix:

x     <- 1:100
wnc   <- c(0.123, 0.263, 0.223)
dypol <- c(.05, .30, .02)

Z <- t(sapply(x, function(x)dypol * x ^ 2 - dypol + wnc))
apply(Z, 2, cumsum)
flodel
  • 87,577
  • 21
  • 185
  • 223