I want to loop through a list and work with its nth element, but the list can be empty:
l <- list()
for(i in 1:length(l)) a <- l[[i]]
If the list has 1 element, everything is fine.
But if the list is empty, length(l) equals to zero, so the loop will try to run twice and count down i from 1 to 0. This throws an error, as l[[1]]
doesn't exist:
> Error in l[[i]] : subscript out of bounds
Is there a better way to skip the for loop than checking if length(l) is bigger than zero?