简体   繁体   English

如何将 lapply 的结果组合到 data.frame?

[英]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.说,我有一个向量和一个带有一个参数的函数,它返回一个 data.frame。 I want to apply the function to each element of the vector and combine the results to one big data.frame.我想将该函数应用于向量的每个元素,并将结果组合到一个大 data.frame 中。

I've got the working command below with lapply and rbind.我有以下带有 lapply 和 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.我对 plyr 有一些想法,但我想避免使用 plyr,因为我想改用 dplyr。

 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:您还可以使用data.tablerbindlist如下:

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

Without setDF rbindlist returns a data.table instead of a data.frame没有setDF rbindlist 返回一个data.table而不是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))
      })
    }))
  }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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