【问题标题】:How to facilitate the output when splitting data.frame in the list?在列表中拆分data.frame时如何方便输出?
【发布时间】:2016-10-14 14:56:44
【问题描述】:

我在列表中有 data.frame 对象。但是,我打算通过将其分数与给定阈值进行比较来拆分 myList。特别是,我想让我的函数只返回得分大于阈值的data.frame,同时我将小于阈值的那个导出为csv文件(因为我将进一步处理保存的data.frame,而导出的data.frame将列在最后的摘要中)。我知道首先拆分 data.frame 然后将它们导出为 csv 文件,然后进一步处理所需的文件更容易。但我想在一个包装函数中轻松实现这一点。谁能指出我如何更有效地促进我的功能输出?有什么想法吗?

小例子:

mylist <- list(
  foo=data.frame( from=seq(1, by=4, len=16), to=seq(3, by=4, len=16), score=sample(30, 16)),
  bar=data.frame( from=seq(3, by=7, len=20), to=seq(6, by=7, len=20), score=sample(30, 20)),
  cat=data.frame( from=seq(4, by=8, len=25), to=seq(7, by=8, len=25), score=sample(30, 25)))

我打算这样拆分它们:

func <- function(list, threshold=16, ...) {
  # input param checking
  stopifnot(is.numeric(threshold))
  reslt <- lapply(list, function(elm) {
    res <- split(x, c("Droped", "Saved")[(x$score > threshold)+1])
    # FIXME : anyway to export Droped instance while return Saved
  })
}

在我的草图函数中,我打算将每个 data.frame 中的 Droped 实例导出为 csv 文件,同时从每个 data.frame 中返回 Saved 实例作为输出并将其用于进一步处理。

我试图在我的函数中实现这一点,但我的方法在这里效率不高。谁能指出我如何轻松地做到这一点?有谁知道这样做有什么有用的技巧可以更优雅地提示我的预期输出?提前致谢。

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    您可以将这两个进程滚动到对lapply 的调用中,如下所示:

    # function to perform both tasks on one data frame in mylist
    splitter <- function(i, threshold) {
    
      require(dplyr)
    
      DF <- mylist[[i]]
    
      DF %>%
        filter(score <= threshold) %>%
        write.csv(., sprintf("dropped.%s.csv", i), row.names = FALSE)
    
      Saved <- filter(DF, score > threshold)
    
      return(Saved)
    
    }
    
    # now use the function to create a new list, my list2, with the Saved 
    # versions as its elements. the csvs of the dropped rows will get created
    # as this runs. 
    mylist2 <- lapply(seq_along(mylist), function(i) splitter(i, 16))
    

    【讨论】:

    • 您可以通过修改对write.csv的调用的sprintf部分中的路径来控制csv文件的去向。如果您想以编程方式创建新文件夹,您可以在调用 lapply 之前使用 dir.create
    • 关于函数输出,如何使它们成为命名列表而不是生成默认索引列表?
    • 我可以这样尝试: names(mylist2)
    • 当然,这似乎是最简单的方法。
    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2013-01-27
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多