Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangerous for loop idiom?

Tags:

r

taking an example from An 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 the case where you need a handle on the current index. This however breaks in the case of an empty list since 1:0 is not an empty vector. What is the idiom I should use for iterating over list/vector indices when you aren't guaranteed a non-empty list? I'm thinking if(length(yc)) for(i in 1:length(yc)) { ... but is there a nicer way?

like image 425
Keith Avatar asked Sep 01 '11 19:09

Keith


1 Answers

You're looking for seq_along.

> seq_along(as.list(1:2))
[1] 1 2
> seq_along(list())
integer(0)
like image 159
Aaron left Stack Overflow Avatar answered Sep 21 '22 23:09

Aaron left Stack Overflow