[R] Multiple counters in a single for loop

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Sun Aug 26 12:59:57 CEST 2018


On 26/08/2018 3:10 AM, Jeremie Juste wrote:
> Duncan Murdoch <murdoch.duncan using gmail.com> writes:
> 
>>> for ( i in 1:length(var1)){
>>
>> This is generally a bad idea:  if length(var1) == 0, it does the wrong
>> thing, since 1:0 is c(1L, 0L).  Better to use
>>
>> for ( i in seq_along(var1) ) {
>>
> 
> 
> granted. One should check the validity of their variables before using
> them but I argue that seq_along does not protect you from the
> unexpected behaviour.

I don't see why you argue that.  seq_along(var1) will give an empty 
vector if var1 is empty, so the loop won't run at all.

> 
> If the length of var1 should not be 0 so
> 
> stopifnot(length(var) > 0)
> for ( i in 1:length(var1)){
> 
>      elem1 <-var1[i]
>      elem2 <-  var2[i]
> 
> }

That's a possibility (I made your >0 correction), but maybe having 
length 0 isn't something that should trigger a fatal error, maybe it's 
just that no elements met some condition.

Duncan Murdoch




More information about the R-help mailing list