代码之家  ›  专栏  ›  技术社区  ›  David

带有变量的r drake文件输出名

  •  0
  • David  · 技术社区  · 7 年前

    我正在使用 drake 要创建多个输出文件,我要在其中通过变量指定路径。有点像

    outpath <- "data"
    outfile <- file.path(outpath, "mydata.csv")
    write.csv(df, outfile)
    

    但是 file_out 除了文字字符之外,似乎无法处理给它的参数。

    给出一个小的代码示例:

    代码设置

    library(drake)
    
    outpath <- "data"
    # for reproducibility only
    if (!dir.exists(outpath)) dir.create(outpath)
    
    make_data <- function() data.frame(x = 1:10, y = rnorm(10))
    

    工作代码

    直接指定文件:

    p0 <- drake_plan(
      df = make_data(),
      write.csv(df, file_out("data/mydata0.csv"))
    )
    make(p0)
    #> target file "data/mydata0.csv"
    

    失效代码

    使用 file.path 建造出口

    p1 <- drake_plan(
      df = make_data(),
      write.csv(df, file_out(file.path(outpath, "mydata1.csv")))
    )
    make(p1)
    #> target file "mydata1.csv"
    #> Error: The file does not exist: mydata1.csv
    #> In addition: Warning message:
    #> File "mydata1.csv" was built or processed,
    #> but the file itself does not exist. 
    

    我想德雷克只找到文本字符串作为目标,而不是 file.path(...) 例如,这也失败了

    p2 <- drake_plan(
      df = make_data(),
      outfile = file.path(outpath, "mydata1.csv"),
      write.csv(df, file_out(outfile))
    )
    #> Error: found an empty file_out() in command: write.csv(df, file_out(outfile))
    

    知道怎么解决吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   landau    6 年前

    对不起,我来晚了。我可以更容易地找到问题 drake-r-package 标签。

    感谢@alexis提供了相关线程的链接。通配符在这里真的很有用。

    所有目标、输入文件和输出文件都需要预先显式命名。就是这样 drake 可以在不计算计划中任何代码的情况下找出所有依赖关系。自从 公鸭 负责确定何时构建哪些目标,我可能不会在将来的开发中放松这一要求。

    就其价值而言,整洁的评估也可能有所帮助。

    library(drake) # version 5.3.0
    pkgconfig::set_config("drake::strings_in_dots" = "literals")
    file <- file.path("dir", "mydata1.csv")
    drake_plan(
      df = make_data(),
      output = write.csv(df, file_out(!!file))
    )
    #> # A tibble: 2 x 2
    #>   target         command                                       
    #> * <chr>          <chr>                                         
    #> 1 df             make_data()                                   
    #> 2 output         "write.csv(df, file_out(\"dir/mydata1.csv\"))"
    

    编辑:元编程

    我最近添加了 lengthy section of the manual on metaprogramming . 如果您希望以更灵活和自动化的方式生成工作流计划数据框架,则可能必须放弃 drake_plan() 功能和做更多涉及整洁的评价。这个 discussion on the issue tracker 也是相关的。

    推荐文章