【问题标题】:R - lapply - getting data frames back out of lists?R - lapply - 从列表中获取数据帧?
【发布时间】:2020-05-21 09:27:37
【问题描述】:

我和这个人有同样的问题:returning from list to data.frame after lapply

虽然他们解决了他的具体问题,但实际上没有人回答他最初关于如何从列表中获取数据帧的问题。

我有一个数据框列表:

dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)

我想对它们进行过滤/替换等。

所以我的功能是:

DoThis = function(x){
  filter(x, year >=2015 & year <=2018) %>% 
  replace(is.na(.), 0) %>%
  adorn_totals("row")

}

我使用 lapply 在它们上运行函数,如下所示:

a = lapply(dfPreList, DoThis) 

正如另一篇文章所述,这些数据帧现在卡在此列表中(a),我需要一个for loop 才能将它们取出,这不是正确的做法。

这是我目前将函数应用于数据帧然后将它们取出的工作方式:

dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)
dfPreListstr= list('yearlyFunding', 'yearlyPubs', 'yearlyAuthors')

DoThis = function(x){
  filter(x, year >=2015 & year <=2018) %>% 
  replace(is.na(.), 0) %>%
  adorn_totals("row")

}

a = lapply(dfPreList, DoThis)

for( i in seq_along(dfPreList)){

  assign(dfPreListstr[[i]], as.data.frame(a[i]))

}

有没有办法做到这一点而不必依赖for loops 和数据帧的字符串名称? IE。与lapply 的单线?

非常感谢您的帮助

【问题讨论】:

    标签: r lapply


    【解决方案1】:

    您可以为列表指定名称,然后使用list2env

    dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)
    a = lapply(dfPreList, DoThis) 
    names(a) <- c('yearlyFunding', 'yearlyPubs', 'yearlyAuthors')
    list2env(a, .GlobalEnv)
    

    【讨论】:

    • 谢谢。然而。 lapply 返回一个列表列表,我对你的代码有点困惑?即我看不到“a = lapply(dfPreList, DoThis)”的来源?即我想解开'a',它的结果是 lapply 存储为列表。谢谢!
    • @ScoutEU 好的。更新了答案。你现在可以检查吗?
    • 非常感谢,这太完美了:)
    【解决方案2】:

    另一种方法是unlist列表,然后将内容转换为数据框。

    dfPreList = list(yearlyFunding, yearlyPubs, yearlyAuthors)
    a = lapply(dfPreList, DoThis)
    names(a) <- c('yearlyFunding', 'yearlyPubs', 'yearlyAuthors')
    
    yearlyFunding <- data.frame(matrix(unlist(a$yearlyFunding), nrow= nrow(yearlyFunding), ncol= ncol(yearlyFunding)))
    yearlyPubs <- data.frame(matrix(unlist(a$yearlyPubs), nrow= nrow(yearlyPubs), ncol= ncol(yearlyPubs)))
    yearlyAuthors <- data.frame(matrix(unlist(a$yearlyAuthors), nrow= nrow(yearlyAuthors), ncol= ncol(yearlyAuthors)))
    

    由于unlist函数返回一个向量,我们先生成一个矩阵,然后将其转换为数据框。

    【讨论】:

    • 嘿 phago,虽然有用,但我故意让我的帖子简短,所以错过了大约 30 个数据帧。我想要一个迭代过程,这样我就不必输入 30 行未列出的内容。不过谢谢!
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2018-06-08
    • 2013-10-15
    • 2020-04-04
    • 2012-05-22
    相关资源
    最近更新 更多