[R] Creating a loop with an indefinite end term
Charilaos Skiadas
cskiadas at gmail.com
Tue Apr 10 19:59:33 CEST 2012
On Apr 10, 2012, at 1:08 PM, Steve Lavrenz wrote:
> I definitely need a loop - the example I gave was only a simple
> one. Say I
> want to do more complex calculations in each step, such that the
> numeric
> difference between consecutive terms is not constant.
>
>
>
> I will try out some of the methods that have been shared so far.
> Thank you!
>
One thing to keep in mind is that, R is pretty darn well optimized
for doing vector calculations. Depending on your problem, it might be
worth it to just compute a lot more steps if you can do it in a
vectorized form avoiding a loop, then do something like
x[x<100]
to only pick out the values that are less than 100. So I think you
should ask yourself if you really really need to stop the loop at
that point. Not knowing more details about the actual problem you are
trying to solve, I can't answer that, but in general in R if you can
do something without loops and using vectorization instead, then that
is the "R way to do it". But it really depends on the particular
problem whether that is doable or not.
If you do indeed need to use a loop, it would probably help indeed
not have to constantly change the size of the vector, as Drew points
out. If you know a reasonable upper bound for how many terms will be
needed, reserve that many. If not, maybe you could reserve them in
chunks of say 100; so start with a vector of size 100, and if you
fill that up during the loop add another 100 etc.
> -Steve
Haris Skiadas
Department of Mathematics and Computer Science
Hanover College
>
> From: Jean V Adams [mailto:jvadams at usgs.gov]
> Sent: Tuesday, April 10, 2012 12:38 PM
> To: Steve Lavrenz
> Cc: r-help at r-project.org
> Subject: Re: [R] Creating a loop with an indefinite end term
>
>
>
>
> Do you need a loop at all?
>
> Will this do the trick?
>
> seq(from=0, to=100, by=5)
>
> Jean
>
>
> Steve Lavrenz wrote on 04/10/2012 09:48:34 AM:
>
>> Everyone,
>>
>> I'm very new to R, especially when it comes to loops and
>> functions, so
>> please bear with me if this is an elementary question. I cannot
>> seem to
>> figure out how to construct a loop which runs a function until a
>> certain
>> value is computed. For example, say I have the following:
>>
>> num = numeric (10)
>> num [1] = 0
>> for (i in 2:10) {
>> num [i] = num [i-1] + 5
>> }
>>
>> This adds 5 to the preceding spot of a vector of length 10 to get the
> value
>> in the current spot. However, say I don't just want to run this
>> for 10
>> spots; rather I want to run it until a certain value (say, 100) is
> computed.
>> How I construct my loop to do this?
>>
>> Thanks!
>
More information about the R-help
mailing list