Skip to content
Prev 277321 / 398506 Next

Very simple loop

x <-c(0:200)
dat <- data.frame(
  A = dpois(x,exp(4.5355343)),
  B = dpois(x,exp(4.5355343 + 0.0118638)),
  C = dpois(x,exp(4.5355343  -0.0234615)),
  D = dpois(x,exp(4.5355343 + 0.0316557)),
  E = dpois(x,exp(4.5355343 + 0.0004716)),
  F = dpois(x,exp(4.5355343 + 0.056437)),
  G = dpois(x,exp(4.5355343 + 0.1225822)))

## using a looping approach
## instantiate a vector to hold results
results <- vector("numeric", length = length(x))

for(i in 1:201) {# R starts indexing at 1, not 0
  results[i] <- dat[i, "A"] + dat[i, "B"] + dat[i, "C"] +
    dat[i, "D"] + dat[i, "E"] + dat[i, "F"] + dat[i, "G"]
}

## find and plot cumulatively values
plot(x, cumsum(results))

You may be wondering why I put all the variables in a data frame.  It
is because it will be much easier in the long run.  This accomplishes
the same thing as the loop, with a fraction of the effort and much
much faster (loops can be slow in R, and vectorizing is preferred).

plot(x, cumsum(rowSums(dat)))

rowSums() is a vectorized function that finds the (duh) sums of each
row, then I just find the cumulative sum, and plot.

Hope this helps,

Josh
On Mon, Nov 14, 2011 at 7:59 AM, Davg <davidgrimsey at hotmail.com> wrote: