Stack a dataframe on itself multiple times in R?

Viewed 52

I would like to stack a dataframe 100 times on itself, with an additional column indicating the iteration number, similar to what dplyr::bind_rows(..., .id = "id") does. Or is there a way I can save 100 times my dataframe into a single list and then use data.table::rbindlist()?

library(dplyr)
bind_rows(iris, iris, .id = "id") #This stacks the data only twice
library(data.table)
rbindlist(list(iris, iris), idcol = "id")
2 Answers

We could use replicate to return the datasets in a list and then use bind_rows or rbindlist

library(dplyr)
n <- 5
replicate(n, iris, simplify = FALSE) %>%
    bind_rows(.id = 'id')

Or another option is purrr::rerun

library(purrr)
n %>%
   rerun(iris) %>% 
   bind_rows(.id = 'id')

A base R option with rbind + lapply + cbind

> n <- 100

> do.call(rbind, lapply(seq(n), function(k) cbind(id = k, iris)))
Related