6

I just need to replicate my data.frame n times (e.g. 100) and save all the outputs into a list.

It should be quite easy and straightforward but I could not find any solution yet.

Fake data.frame:

df = read.table(text = 'a b
1 2
5 6
4 4
11 78
23 99', header = TRUE)
alistaire
  • 42,459
  • 4
  • 77
  • 117
aaaaa
  • 149
  • 2
  • 18
  • 44

3 Answers3

13

With lapply:

df_list <- lapply(1:100, function(x) df)
Sraffa
  • 1,658
  • 12
  • 27
  • This solved a similar problem for me as well. I am curious about the syntax. Why does this result in basic replication? Is the function(x) basically a non-function, so you are repeating "df" 1:100 times but without doing anything to it? – PortMadeleineCrumpet Nov 16 '21 at 00:11
9

We can use replicate

n <- 100
lst <- replicate(n, df, simplify = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
2

You can use rep if you wrap it in list, as rep tries to return the same type of object you pass it:

df_list <- rep(list(df), 100)

str(df_list[1:2])
#> List of 2
#>  $ :'data.frame':    5 obs. of  2 variables:
#>   ..$ a: int [1:5] 1 5 4 11 23
#>   ..$ b: int [1:5] 2 6 4 78 99
#>  $ :'data.frame':    5 obs. of  2 variables:
#>   ..$ a: int [1:5] 1 5 4 11 23
#>   ..$ b: int [1:5] 2 6 4 78 99
alistaire
  • 42,459
  • 4
  • 77
  • 117