Replicate same data.frame n times and save them into a list
Asked Answered
C

3

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)
Comedo answered 8/5, 2017 at 17:31 Comment(2)
Replicate? Isn't that just the same output, over and over?Bicentennial
yes, exactly.....I need it because I want to manipulate them eventually in n different waysComedo
S
13

With lapply:

df_list <- lapply(1:100, function(x) df)
Stulin answered 8/5, 2017 at 17:34 Comment(1)
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?Wring
F
9

We can use replicate

n <- 100
lst <- replicate(n, df, simplify = FALSE)
Feverous answered 8/5, 2017 at 17:33 Comment(1)
If this helped, you should mark the checkbox beside it.Bicentennial
W
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
Winifield answered 8/5, 2017 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.