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
exits.
Hope this helps
-Don
(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
925-423-1062
On 4/6/13 7:36 PM, "Baylee Smith" <bayywater at gmail.com>
wrote:
>Hi,
>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].
>
>Thanks!
>
> [[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.