首页 > 解决方案 > 如何正确地将示例添加到写入文件的 R 函数中

问题描述

将文档写入旨在写入文件的 R 函数的正确方法是什么?

根据 CRAN 的评论:

请确保您的函数不会在默认情况下或在用户主文件空间的示例/小插图/测试中写入。CRAN 政策不允许这样做。如果用户已指定目录,请仅写入/保存文件。在您的示例/小插图/测试中,您可以写入 tempdir()

例子:

下面的示例将使用tempdir()函数生成路径

tempdir()
> "C:\\Users\\username\\AppData\\Local\\Temp\\RtmpiG8whL"

这样提交包裹可以吗?

#' @examples
#' x <- sd(1:10)
#' my_fun(x, path = tempdir())

my_fun <- function(x, path = "", file_n = "test"){
 file_p <- file.path(path, paste0(file_n, ".csv"))
 write.csv(x, file_p)
}

不做测试的例子

或者任何写入文件的函数都应该明确避免测试示例?

#' @examples
#' \donttest{ 
#' x <- sd(1:10)
#' my_fun(x, path = tempdir())
#' }

my_fun <- function(x, path = "", file_n = "test"){
 file_p <- file.path(path, paste0(file_n, ".csv"))
 write.csv(x, file_p)
}

此外,检查此类问题的最佳方法是什么?

devtools::check()在 中运行后不应创建任何tempdir()内容,这是正确的吗?

标签: rr-package

解决方案


由于某种原因,函数tempdir()一直在临时目录中写入文件

作为一种解决方法,我最终tempfile()在我的示例中使用。这使临时文件夹保持清洁......

#' @examples
#' x <- sd(1:10)
#' my_fun(x, path = tempfile())

my_fun <- function(x, path = "", file_n = "test"){
 file_p <- file.path(path, paste0(file_n, ".csv"))
 write.csv(x, file_p)
}

推荐阅读