如何导出过滤后的数据帧到所需的文件夹动态



我已经阅读了文件夹中的csv文件列表,现在我打算将它们过滤掉给定的阈值,其中每个数据帧中的删除行必须以动态方式导出到所需的文件夹,同时保存行返回作为输出。然而,我实现了这个函数来完成这个任务,除了将删除的行作为csv文件写入所需文件夹失败外,它工作得很好。有人能告诉我函数里是什么吗?有什么有效的方法可以动态地在特定文件夹中写入data.frame吗?我如何纠正执行?你知道吗?

可再生的数据:

myData <- list(
  df_1 = data.frame( L1=seq(3, by=4, len=16), L2=seq(7, by=4, len=16), score=sample(30, 16)),
  df_2 = data.frame( L1=seq(6, by=7, len=20), L2=seq(14, by=7, len=20), score=sample(30, 20)),
  df_3 = data.frame( L1=seq(11, by=8, len=25), L2=seq(19, by=8, len=25), score=sample(30, 25))
  )

我实现了这个函数,它工作得很好,除了不需要写csv文件:

func <- function(mlist, threshold=NULL, outDir=getwd(), .fileName=NULL, ...) {
  if(!dir.exists(outDir)) {
    dir.create(file.path(outDir))
    setwd(file.path(outDir))
  }
  rslt <- lapply(mlist, function(x) {
    .drop <- x[x$score < threshold,]
    # FIXME : write droped rows of each data.frame into specific folder
    write.csv(.drop, sprintf("drop.%s.csv", x), row.names = FALSE)
    .save <- x[x$score >= threshold,]
    return(.save)
  })
  return(rslt)
}

这就是我打算在特定位置写csv文件:与。initpath .initPath = getwd()连接,创建新文件夹并在那里写csv文件。我不知道我的实现出了什么问题,我得到了一个错误。

我如何写从每个data.frame到特定文件夹的删除行动态?有没有什么快速的方法能让这件事发生得更有效率?非常感谢。

目前,在您的write.csv()行中,您正在将数据框对象x连接到具有sprintf()的文件名中。您需要将dataframe对象的名称连接到文件名。

因此,考虑用Map()函数替换lapply() (Mapmapply(func, x, y, SIMPLIFY=FALSE)的包装器,其中为mlist本身和mlist名称传递两个参数)。请注意:您可能认为在原始设置中使用names(x)可以工作,但这会返回相应数据框的列名,这仍然会在连接到文件名字符串时失败。

func <- function(mlist, threshold=NULL, outDir=getwd(), .fileName=NULL, ...) {
  if(!dir.exists(outDir)) {
    dir.create(file.path(outDir))
    setwd(file.path(outDir))
  }
  rslt <- Map(function(x, y) {
    .drop <- x[x$score < threshold,]
    write.csv(.drop, sprintf("drop.%s.csv", y), row.names = FALSE)
    .save <- x[x$score >= threshold,]
    return(.save)
  }, mlist, names(mlist))
  return(rslt)
}
# EXAMPLE
newData <- func(myData, threshold=10)

如果你想保留lapply(),创建临时变量来捕获df对象和df名称。下面还展示了如何通过将这些值传递给args并将它们与sprintf()串联起来来允许动态路径和文件名更改:

func <- function(mlist, threshold=NULL, csvName="", outDir=getwd(), .fileName=NULL, ...) {
  if(!dir.exists(outDir)) {
    dir.create(file.path(outDir))
    setwd(file.path(outDir))
  }
  rslt <- lapply(seq_along(mlist), function(x) {
    df <- mlist[[x]]; dfname <- names(mlist)[x]
    .drop <- df[df$score < threshold,]
    write.csv(.drop, sprintf("%s/%s.%s.csv", outDir, csvName, dfname), row.names = FALSE)
    .save <- df[df$score >= threshold,]
    return(.save)
  })
  return(rslt)
}
# EXAMPLE
newData <- func(myData, threshold=10, csvName=usercsv, outDir=userpath)

最新更新