Home > database >  Alternative to `do.call(rbind.data.frame)` for combining a list of data frames?
Alternative to `do.call(rbind.data.frame)` for combining a list of data frames?

Time:07-01

I have this loop in R that generates 100 random numbers - I know that this can obviously be done without a loop, but for argument sake, I generated 100 random numbers with a loop:

final_results <- list()

for (i in 1:100)

{

index_i = i
num_i = rnorm(1,1,1)
temp_i = data.frame(index_i,num_i)

final_results[[i]] <- temp_i
   
}

results_dataframe <- do.call(rbind.data.frame, final_results)

In the end, I use the do.call(rbind.data.frame) option to convert the list of random numbers into a data frame.

  • I was just curious - are there any alternate options for do.call(rbind.data.frame) that could have been used instead?

Thank you!

CodePudding user response:

We can also use

data.table::rbindlist(final_results)

If you work with "data.table" more often than "data.frame", this is a good choice.

doc

CodePudding user response:

I would implement it as such:

index_i = c()
num_i = c()

for (i in 1:100) {
  
  index_i[i] <- i
  num_i[i] <- rnorm(1,1,1)
  
}

results_dataframe <- data.frame(index_i, num_i)

Extending both methods to 10,000 iterations took my machine 0.1 seconds for this implementation, and 3.6 seconds for the original example.

  • Related