Creating a list of randomized data frames with increasing numbers in names

I want to generate 10 (at work: 50,000) random data frames with seed setup to ensure reproducibility. The seed must be different for each data frame, and its name must increase from df_01, df_02 ... to df_10. Using @akrun's answer, I have coded a loop like this:

# Number of data-frames to be created
n <- 10

# setting a seed vector
x <- 42

# loop
for (i in 1:10) {
        set.seed(x)
        a <- rnorm(10,.9,.05)
        b <- sample(8:200,10,replace=TRUE)
        c <- rnorm(10,80,30)
        lst <- replicate(i, data.frame(a,b,c), simplify=FALSE)
        x <- x+i
}

# name data-frames
names(lst) <- paste0('df', 1:10)

      

Now I have my dataframes but I can't seem to get its random generation. All data are similar. When I replace the lst string with the following code, at least the spent randomization works:

print(data.frame(a,b,c))

      

The triangular extra file will be a hint for leading zeros in dfs names to sort them.

Any help is appreciated, thanks!

+3


source to share


1 answer


You get the same results in all the list items because you create your list from scratch on each iteration with replicate

and replace the previously created one. If you are using a loop for

you don't need to replicate

.

For the sake of reproducibility, I created a vector of seeds before the loop, and then set the seed at each iteration. Leading zeros can be obtained using sprintf

:



## Number of random data frames to create:
n <- 10

## Sample vector of seeds:
initSeed <- 1234
set.seed(initSeed)
seedVec <- sample.int(n = 1e8, size = n, replace = FALSE)

## loop:
lst <- lapply(1:n, function(i){
            set.seed(seedVec[i])
            a <- rnorm(10,.9,.05)
            b <- sample(8:200,10,replace=TRUE)
            c <- rnorm(10,80,30)
            data.frame(a,b,c)
        })
## Set names with leading zeroes (2 digits). If you want
## three digits, change "%02d" to "%03d" etc.
names(lst) <- paste0('df', sprintf("%02d", 1:10))

      

+1


source







All Articles