melbez
melbez

Reputation: 1000

Stacking dataframes from output of iterated function in R

I have written a function and am trying to iterate so that each value from a list becomes the input to the function once.

repeat100 <- function(B) {
  se100 <- replicate(100, bootandse(B))
  bandse <- data.frame("B" = B, "SE" = se100)
}

The output of this function is a dataframe with one column for the value of B that was inputted and another column for the SE. Like this, but with 100 rows.

B  SE
1  2
1  4
1  3

I have an object B with several values. I am trying to iterate repeat100() over each value of B.

B <- c(1, 4, 6, 20, 30)

How can I get the resulting output to be a dataframe that has the output of each repeat100() for each value of B stacked like this?

B  SE 
1  2
1  3
1  2 
4  5
4  3 
4  2

Upvotes: 0

Views: 37

Answers (2)

akrun
akrun

Reputation: 887223

We can use rbindlist from data.table

library(data.table)
rbindlist(lapply(B, repeat100))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389047

Use lapply with rbind to combine the data in one dataframe.

result <- do.call(rbind, lapply(B, repeat100))

Or purrr::map_df which is shorter.

purrr::map_df(B, repeat100)

Upvotes: 2

Related Questions