Pitfalls

  • Preallocate output containers to avoid slow code.

  • Beware that 1:length(v) when v has length 0 results in a iterating backwards over 1:0, probably not what is intended. Use seq_along(v) instead.

  • When iterating over S3 vectors, use [[]] yourself to avoid stripping attributes.

xs <- as.Date(c("2020-01-01", "2010-01-01"))
for (x in xs) {
  print(x)
}
#> [1] 18262
#> [1] 14610

vs. 

for (i in seq_along(xs)) {
  print(xs[[i]])
}
#> [1] "2020-01-01"
#> [1] "2010-01-01"