简体   繁体   中英

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

Try

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM