JerryWho
JerryWho

Reputation: 3105

How to combine result of lapply to a data.frame?

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))))

Upvotes: 17

Views: 17433

Answers (3)

&#214;mer An
&#214;mer An

Reputation: 664

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))
      })
    }))
  }))

Upvotes: 1

Rentrop
Rentrop

Reputation: 21497

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

Upvotes: 4

Khashaa
Khashaa

Reputation: 7373

Try

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

Upvotes: 28

Related Questions