Danger for idiom cycle?

taking an example from Introduction to R

xc <- split(x, ind) yc <- split(y, ind) for (i in 1:length(yc)) { plot(xc[[i]], yc[[i]]) abline(lsfit(xc[[i]], yc[[i]])) } 

It seems that for(i in 1:length(yc)) { ... is an idiom for iterating over a list or vector in case you need a handle to the current index. This, however, breaks down in the case of an empty list, since 1:0 not an empty vector. What idiom should I use to iterate over list / vector indices if you are not guaranteed a non-empty list? I think if(length(yc)) for(i in 1:length(yc)) { ... , but is there a better way?

+6
source share
4 answers

You are looking for seq_along .

 > seq_along(as.list(1:2)) [1] 1 2 > seq_along(list()) integer(0) 
+11
source

You can use seq_along :

 for(i in seq_along(yc)) {...} 

I am sure this circumvents the problem and should be a little faster.

+7
source

This question is highlighted on page 75 of The R Inferno: http://www.burns-stat.com/pages/Tutor/R_inferno.pdf

It tells you a few more ways to make your cycle go wrong.

+4
source

For those who accidentally stumble upon this - if you want the index vector to be based on possibly zero length, and not on another vector, you can safely use seq(1, length.out = L) , where L can be any non-negative integer. This will give you integer(0) if L == 0 and 1:L otherwise.

Of course, the other solutions given here are more concise if L == length(something) , but I had a problem when it was not, so I decided to write it for posterity.

Also seq(1, length.out = L) can be abbreviated as seq_len(L) , which according to ?seq is faster.

0
source

Source: https://habr.com/ru/post/896442/


All Articles