Consider the code below:
foo = list("First List", 1, 2, 3)
bar = function(x) {
cat("The list name is:", x[[1]], "\nThe items are:\n")
for (i in 2:length(x))
cat(x[[i]], "\n")
}
bar(foo)
The result will be:
The list name is: First List
The items are:
1
2
3
Now consider passing a list with no items, but a name:
baz = list("Second List")
bar(baz)
The result would be:
The list name is: Second List
The items are:
Error in x[[i]] : subscript out of bounds
The error is because 2:length(x) will produce a sequence of c(2, 1) for the latter case bar(baz), so it tries to access baz[2] and it does not exist.
How to simply prevent this unwanted reverse iteration in a for loop in R?
No need to loop over the list indices, you can just loop over a sub-list:
If there is a single item in your list, the sub-list will be empty and the for loop will be skipped.
Edit: As GavinSimpson points out, this works well because your particular case did not really need to loop over indices. If indices were absolutely needed, then you would have to loop over
seq_along(x[-1])instead ofx[-1]as Andrie showed.