13
votes

Say, I have a vector and a function with one argument which returns a data.frame. I want to apply the function to each element of the vector and combine the results to one big data.frame.

I've got the working command below with lapply and rbind. But it looks to me a little bit "unnatural". Is there a better, more clear way? I've got some ideas with plyr but I would like to avoid plyr because I would like to use dplyr instead.

 my_vector <- c(1,2,3)
 my_function <- function(a){
   unif <- runif(a)
   norm <- rnorm(a)
   return(data.frame(unif=unif, norm=norm))
 }

 as.data.frame(do.call(rbind,(lapply(my_vector, my_function))))
3

3 Answers

24
votes

Try

library(dplyr)
lapply(my_vector, my_function) %>% bind_rows()
3
votes

You can also use data.table's rbindlist as follows:

require(data.table)
df <- setDF(rbindlist(lapply(my_vector, my_function)))

Without setDF rbindlist returns a data.table instead of a data.frame

0
votes

Solution for nested lists:

  result = bind_rows(lapply(list1, function(x) {
    bind_rows(lapply(list2, function(y) {
      lapply(list3, function(z) {
        read.delim(paste0(x, "_", y, "_", z))
      })
    }))
  }))