R: For Loop with the Colon Operator and the Length of an Empty Vector

Viewed 189

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?

1 Answers

Yes, the better way is to use seq_along to loop over a vector.

foo = c("one","two","three")
for (bar in seq_along(foo)) {
   print(bar)
}

#[1] 1
#[1] 2
#[1] 3

foo = c()
for (bar in seq_along(foo)) {
  print(bar)
}
#Prints nothing

edit based on jogos comment: Indexing can be used to access the vectors elements directly:

foo = c("one","two","three")
for (bar in foo) {
   print(bar)
}

#[1] "one"
#[1] "two"
#[1] "three"

foo = c()
for (bar in foo) {
   print(bar)
}
#Prints nothing
Related