for()
loops
But what if you want to save the output of the loops in one list or vector?
Pre-allocate memory to your vector / data frame / list, then fill in the values!
Growing an object takes many times longer (e.g. doing x <- c(x, new)
in the for
loop).
paths <- dir("data/gapminder", pattern = "\\.xlsx$", full.names = TRUE)
files <- vector("list", length(paths))
seq_along(paths)
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12
for (i in seq_along(paths)) {
files[[i]] <- readxl::read_excel(paths[[i]])
}
do.call(rbind, files)
#> # A tibble: 1,704 × 5
#> country continent lifeExp pop gdpPercap
#> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 Afghanistan Asia 28.8 8425333 779.
#> 2 Albania Europe 55.2 1282697 1601.
#> 3 Algeria Africa 43.1 9279525 2449.
#> 4 Angola Africa 30.0 4232095 3521.
#> 5 Argentina Americas 62.5 17876956 5911.
#> 6 Australia Oceania 69.1 8691212 10040.
#> # ℹ 1,698 more rows