I would like to combine multiple dataframes, as output of a function, into one big dataframe in R.
I am simulating data within a function, e.g.:
set.seed(123)
x <- function(){
return( data.frame( matrix(rnorm(10, 1, .5), ncol=2) ) )
}
I would like to run multiple simulations and tie the dataframes together.
Attempt
set.seed(123)
x_improved <- function(sim_nr){
df <- data.frame( matrix(rnorm(10, 1, .5), ncol=2) ) # simulate data
sim_nr <- rep(sim_nr, length(df[,1])). # add reference number
df <- cbind(df, sim_nr) # bind columns
return(df)
}
list_dataframes <- lapply(c(1,2,3), x_improved) # create list of dataframes
df <- do.call("rbind", list_dataframes) # convert list to dataframe
The code above does so, see "Expected output" below.
Expected output:
> df
X1 X2 sim_nr
1 0.4660881 0.1566533 1
2 0.8910125 1.4188935 1
3 0.4869978 1.0766866 1
4 0.6355544 0.4309315 1
5 0.6874804 1.6269075 1
6 1.2132321 1.3443201 2
7 0.8524643 1.2769588 2
8 1.4475628 0.9690441 2
9 1.4390667 0.8470187 2
10 1.4107905 0.8097645 2
11 0.6526465 0.4384457 3
12 0.8960414 0.7985576 3
13 0.3673018 0.7666723 3
14 2.0844780 1.3899826 3
15 1.6039810 0.9583155 3
Question:
Is this the proper (or R) way to address this problem? Are there more efficient (or convenient) solutions?