编写一个读取示例文件的R包小插图?

时间:2012-07-10 20:38:40

标签: r sweave

我正在尝试为R中的包写一个小插图。我一直关注a tutorial from Vanderbilt University以及the offical documentation

我创建了一个.Rnw Sweave文件并将其放入我的包中的子目录inst/doc中。在同一个子目录inst/doc中,我放了一个包含一些示例文本文件的文件夹example。我的包有一个函数myparser(path),我想在小插图中演示; myparser(path)通过使用绝对路径名path读取文件夹内的文本文件来创建多个数据框。

然后我使用R CMD CHECK检查了包,并收到此错误:

* checking running R code from vignettes ...
   ‘mypackage-vignette.Rnw’ using ‘UTF-8’ ... failed
 ERROR
Errors in running code in vignettes:
when running code in ‘mypackage-vignette.Rnw’
  ...
> library(mypackage)
Loading required package: ggplot2

> myparser("/example/")
Warning in file(file, "rt") :
  cannot open file '/example/': No such file or directory

  When sourcing ‘mypackage-vignette.R’:
Error: cannot open the connection
Execution halted

我看到我尝试使用文件夹的相对路径不起作用(可能应该对我很明显),但我仍然不确定如何解决这种情况。我不想将path替换为我的计算机上的文件夹的绝对路径,因为那时插图的代码将无法在其他人的计算机上重现。

如何在包中包含示例文件,以便晕图的代码可以重现?我是否以正确的方式解决了这个问题?

(抱歉,这个问题本身不具有更高的可重复性!)

1 个答案:

答案 0 :(得分:9)

您可以使用system.file('doc', 'example', package = 'mypackage')来引用该目录,因为R会在构建小插图之前安装软件包,正如您在运行R CMD build mypackage时所看到的那样。