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?
You're looking for seq_along
.
> seq_along(as.list(1:2))
[1] 1 2
> seq_along(list())
integer(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With