Till now I worked fine with my for loops though vectors using:
foo = c("one","two","three")
for (bar in 1:length(foo)) {
print(bar)
}
#[1] 1
#[1] 2
#[1] 3
However, I've noticed that the loop is accessed even if the vector is empty:
foo = c()
for (bar in 1:length(foo)) {
print(bar)
}
#[1] 1
#[1] 0
Of course I could use an IF statement (if (length(foo)!=0)), but I'm sure there is a better way to do this.
Maybe I have a too "pythonic" strategy since there I wouldn't have the problem with
foo = []
for bar in foo:
print(bar)
What is the best way to prevent an access of the for loop if my vector is empty?