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?