[R] While loop history

MacQueen, Don macqueen1 at llnl.gov
Mon Apr 8 16:46:42 CEST 2013

There are a number of different ways to do this, so it would have been
helpful if you had set the context with a stripped down example. That
said, here are some pointers:

> x1 <- NULL
> x1 <- c(x1,3)
> x1
[1] 3
> x1 <- c(x1,4)
> x1
[1] 3 4

So you see that you can add elements to the end of a vector (extend its
length) at any time.

For your case initialize two vectors, x1 and x2, as NULL before the while
loop, then inside the loop do as above.

That will be fine for small or modest length vectors. If they get too
large, it will be better to pre-allocate the vectors. Here's an example.

looplen <- 1e6

x1 <- x2 <- numeric(looplen)

for (i in seq(looplen) {
  ## do whatever
  x1[i] <- x[1]
  x2[i] <- x[2]

Or the same thing with a while loop, but you'll have to calculate the
index value. In which case you probably don't know ahead of time how long
to make them. Make them plenty long, then shorten them after the loop

Hope this helps

(As an aside, I disagree that loops are seldom a good solution. It
depends. Sometimes code written with loops is easier to read and
understand than if written with, say, lapply. So unless there's a big
performance hit, why not write code that's easier to understand?

It is, however, quite common for those new to R is to write loops where
it's not necessary to use any kind of loop at all, due to R's vectorized
nature (whereas the same problem in some other language would require a
loop). Your case may be one of these, and given your description it
wouldn't be surprising, but without that stripped down example it's
impossible to say.)

Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550

On 4/6/13 7:36 PM, "Baylee Smith" <bayywater at gmail.com> wrote:

>I am new at R and still trying to get the hang of things.
>I am running a while loop and wish to save the results of each iteration.
>The results are a vector x of length two and I wish to save the results of
>each iteration as two vectors, one for x[1] and the other for x[2].
>	[[alternative HTML version deleted]]
>R-help at r-project.org mailing list
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list