Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add external data file into developing R package?

Tags:

r

r-package

I am building my R packages in Rstudio, I ran into some unexpected problem when I tired to create package' vignette. when I hit build/load panel in Rstudio, I got vignette error, while package's documentation was created. To possibly solve vignette error I got, I have to add external data to my packages, use this data to compile package vignette accordingly. I used devtools::install() command to install my packages, but inst/ directory is not created. extdata must be located in inst directory. I also used devtools::use_data() to add my data from my PC, but I can't able to add my external data. How can I load external data for my packages ? I think I should not manually create extdata and put external data over there. Why inst/ was not created when I used devtools::install() ? How to add set of csv files as external data into my packages ?

This is the toy helper function I am going to use in my vignette to read external data :

myFunc <- function(myDir, ...) {
  files <- list.files(myDir, full.names = TRUE, "\\.csv$")
  readMe <- lapply(files, read.csv)
  return(readMe)
}

This is the first time I build R packages, getting some common error. My apology if my questions is not well stated.

to find files in inst/, I need to use system.file(), but I don't have this directory, plus myFunc accept file directory to to grab the files and read them as .csv, this is toy code chunk could be executed in vignette file :

```{r}
library(myPkg)
file.1 <- system.file("extdata", "xxx.csv", "myPkg")
file.2 <- system.file("extdata", "yyy.csv", "myPkg")
myFunc(list(file.1, file.2))

```

How can I load external data to my packages in order to compile package vignette by using this data ? Why inst/ not created when I hit devtools::install() ? Can anyone help me how to do this ?Thanks in advance :)

like image 201
Hamilton Avatar asked Dec 01 '16 16:12

Hamilton


1 Answers

You should manually create inst/extdata/file.csv in the base directory for your project (where DESCRIPTION is). You can put all the files you want to access in that directory.

Then to get the files in function examples or your vignette:

files <- lapply(list.files(system.file('extdata', package = 'my_package'), full.names = TRUE), read.csv)

system.file() returns the path to the extdata folder, then list.files() will create a vector of all the files in extdata. Finally, running lapply() with read.csv() should read the contents of all the files into a single list for you.

like image 187
CephBirk Avatar answered Oct 15 '22 15:10

CephBirk