# Define vector
my_vec <- c("a", "b", "c")
# Loop across it
for(k in 1:length(my_vec)){
# Print the kth letter
cat("Processing ", my_vec[[k]], "\n", sep="")
}Processing a
Processing b
Processing c
When iterating a given operation it is common to loop across some integer. For example, maybe you’re looping across a list and want to use the numeric position of each element of the list. Typically, this is accomplished like so:
Processing a
Processing b
Processing c
This works in this case but if the vector of values has no elements, the loop will behave unexpectedly. This is because 1:length of an empty vector returns 1 and 0! Let’s demonstrate this here:
Processing
Processing
[1] 1 0
See how the loop still appears to work but isn’t returning values that might be expected? This can be especially challenging to debug with a more complex (i.e., more realistic) loop. However, we can reformat the first part of the loop to use seq_along instead of 1:length. The loop will still not work but it will be more clear that the issue is with your initial vector of inputs.
seq_along has an along.with argument but for conciseness I’ve let it be implicit in this demo
integer(0)