Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack a dataframe on itself multiple times in R?

Tags:

r

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")
like image 848
CyG Avatar asked Oct 22 '25 05:10

CyG


1 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')
like image 109
akrun Avatar answered Oct 23 '25 17:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!