0

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!

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
stats_noob
  • 5,401
  • 4
  • 27
  • 83
  • Note that you're not converting a list of random numbers into a data frame, it's already a list of data frames. – Caspar V. Jun 30 '22 at 23:28

2 Answers2

2

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

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
1

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.

Caspar V.
  • 1,782
  • 1
  • 3
  • 16