[R] Multiple counters in a single for loop

Jeremie Juste jerem|eju@te @end|ng |rom gm@||@com
Sun Aug 26 09:10:45 CEST 2018


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.

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]

}




More information about the R-help mailing list