参见:https://blog.csdn.net/qazplm12_3/article/details/109349262

很多函数都是在usethis 包中的。

好用的代码

  • use_r
  1. > use_r("peng")
  2. Setting active project to 'D:/01-dir_for_work/02-new-without-packrat'
  3. Creating 'R/'
  4. * Modify 'R/peng.R'
  5. * Call `use_test()` to create a matching test file

会自动在R 目录下创建peng.R 文件。

并且会启动编辑器打开这个文件。

  • use_mit_license
  1. use_mit_license("aa bb")

为作者aa bb 添加mit license 。

  • document

和roxygenize 很相似,也是通过头部注释自动生成R 函数的man 帮助文件的。

单元测试

use_testthat

该函数会在DESCRIPTION 文件中添加Suggests: testthat:

  1. Package: pengToolkit
  2. Title: Some useful functions developed by that man.
  3. Version: 0.0.2
  4. Authors@R: "Mug Peng <mugpeng@foxmail.com> [aut, cre]"
  5. Description: Some useful functions developed by that man.
  6. Depends: R (>= 3.1.1)
  7. License: GPL-2
  8. Encoding: UTF-8
  9. LazyData: false
  10. Date: 2021-05-19
  11. Roxygen: list(markdown = TRUE)
  12. RoxygenNote: 7.1.1
  13. NeedsCompilation: no
  14. Packaged: 2021-05-19 14:54:21 UTC; lenovo
  15. Author: "Mug Peng" [aut, cre]
  16. Maintainer: "Mug Peng" <mugpeng@foxmail.com>
  17. Suggests:
  18. testthat (>= 3.0.0)
  19. Config/testthat/edition: 3

并且创建了tests/testthat文件夹:

03. R 包开发的一些其他技巧 - 图1

接下来我们继续用use_test来创建测试文件,这里选择代码相对简单的set_mirror 函数(其实都很简单啊55~,三个函数加上注释代码一共才107 行):

  1. use_test("set_mirror")

相比起先前的手动定义的test 文件,该函数帮我们新建了一个模板:

  1. test_that("multiplication works", {
  2. expect_equal(2 * 2, 4)
  3. })

修改测试代码,希望修改后对应cran 镜像源为清华,expect_identical 检测左右两边值是否相等:

  1. test_that("set_mirror change the mirror", {
  2. r <- NULL
  3. r[ "CRAN" ] <- "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"
  4. set_mirror()
  5. expect_identical(getOption( "repos" ), r)
  6. })

直接测试即可:

  1. > test()
  2. i<U+00A0>Loading pengToolkit
  3. i<U+00A0>Testing pengToolkit
  4. | OK F W S | Context
  5. / | 0 | set_mirror [1] "Now you successfully take a ladder, go ahead without restriction!"
  6. | 1 | set_mirror
  7. == Results =======================================================
  8. [ FAIL 0 | WARN 0 | SKIP 0 | PASS 1 ]

设置依赖包

有些时候我们想要在自己的包中调用其他包的函数,可以使用use_package()函数。

比如我的函数boost_install_packages 就依赖了BiocManager 包:

  1. use_package("BiocManager")
  2. > use_package("BiocManager")
  3. Adding 'BiocManager' to Imports field in DESCRIPTION
  4. * Refer to functions with `BiocManager::fun()`

这时候如果再打开DESCRIPTION 文件,就添加了import 信息了:
03. R 包开发的一些其他技巧 - 图2