When I run devtools::check() to build my package and the generate the html file of the rmarkdown vignette, I get an error that the data files can't be found. The html file can be built using any of these:
knitr::knit2html('vignettes/myvignette.Rmd') # works fine
devtools::build_vignettes() # works fine
devtools::build() # works fine
But when I run devtools:check() I get:
mydata <- read.csv("data/mycsv.csv")
Warning in file(file, "rt") :
cannot open file 'data/mycsv.csv': No such file or directory
When sourcing 'myvignette.R':
Error: cannot open the connection
Execution halted
How can I get devtools::check() to work? system.file may be relevant but I haven't been able to adapt it to solve my problem. I realise that using rda data files might be a workaround, but I want to use plain text files to store the data in this case.
Here's the myvignette.Rmd, in /vignettes
<!--
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Supplementary materials}
-->
```{r setup, message=FALSE, echo=FALSE}
library(knitr)
# This is necessary to direct knitr to find the
# 'data', and other directories that contain
# files needed to execute this document
# thanks to https://stackoverflow.com/a/24585750/1036500
opts_knit$set(root.dir=normalizePath('../'))
```
```{r}
library(mypackage)
myfunc()
```
```{r}
mydata <- read.csv("data/mycsv.csv", header = FALSE)
mydata
```
Here are the key bits of my example package (the rest is auto-generated by devtools::check and I haven't altered them):
DESCRIPTION
Package: mypackage
Title: What the package does (short line)
Version: 0.1
Authors#R: "First Last <first.last#example.com> [aut, cre]"
Description: What the package does (paragraph)
Depends:
R (>= 3.1.1)
License: MIT
LazyData: true
VignetteBuilder: knitr
Suggests:
knitr
R/myfunction.r
#' my function
#' An example function
#' #export
#'
my_func <- function() Sys.time()
R/docfordata.r
#' #title mycsv
#' #docType data
#' #keywords dataset
#' #format csv
#' #name mycsv
NULL
data/mycsv.csv
1,2,3
11,12,13
22,23,23
I'm working in RStudio 0.98.953, here's the session info
sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
other attached packages:
[1] mypackage_0.1
loaded via a namespace (and not attached):
[1] devtools_1.5 digest_0.6.4 evaluate_0.5.5
[4] httr_0.3 memoise_0.2.1 packrat_0.3.0.107
[7] parallel_3.1.1 Rcpp_0.11.2 RCurl_1.95-4.1
[10] roxygen2_4.0.1 stringr_0.6.2 tools_3.1.1
[13] whisker_0.3-2
UPDATE
Following Andrie's helpful comments I've moved my csv file to inst/extdata and put this line in the vignette read.csv(system.file("extdata/mycsv.csv", package="mypackage"), header = FALSE) and that allows my package to pass both devtools::check and devtools::build. But now it failsknitr::knit2html('vignettes/myvignette.Rmd') anddevtools::build_vignettes()` and at the console with the error messages:
For knit2html:
Quitting from lines 22-29 (vignettes/myvignette.Rmd)
Error in read.table(file = file, header = header, sep = sep, quote = quote, :
no lines available in input
For build_vignettes:
Building mypackage vignettes
Quitting from lines 22-29 (myvignette.Rmd)
Error: processing vignette 'myvignette.Rmd' failed with diagnostics:
no lines available in input
For read.csv(system.file("extdata/mycsv.csv", package = "mypackage"), header = FALSE)
Error in read.table(file = file, header = header, sep = sep, quote = quote, :
no lines available in input
In addition: Warning message:
In file(file, "rt") :
file("") only supports open = "w+" and open = "w+b": using the former
This must be something to do with the wandering inst/ directory that gets moved around when the package is built. So it's fair enough that knit2html and the console might not work, but surely build_vignettes should still work?
Also related: How do I refer to files in the inst directory of an R package from a script in the data directory?
To use a file in the vignette, you can add the file to the vignette folder.
An example of this is in the package tidyr at https://github.com/hadley/tidyr/blob/master/vignettes/tidy-data.Rmd
Try putting your csv file directly to the vignette folder
Related
In the default setting, knitr will use "'pdf' for LaTeX output and 'png' for HTML/markdown". However, I can specify the dev = "png" in the chunk options for the LaTeX output. This feature is very useful to reduce the file size for big vector figure (e.g. maps).
In the previous version of knitr (could be 1.8.*, but not sure), I can specify the dev = "png" (the example below is working for earlier version).
Today I installed the latest version of knitr from github (just now). But the dev='png' is not working for pdf output. I have to use png device for pdf output as I have some big vector figure in pdf format.
The error message is:
Error in (function (filename = "Rplot%03d.png", width = 480, height = 480, :
unused argument (pdf = list(useDingbats = FALSE) Call: <Anonymous> ...
block_exec -> chunk_device -> dev_new -> do.call -> <Anonymous> Execution halted))
How could I fix this problem?
This is my example:
---
output: pdf_document
---
```{r, echo=FALSE, dev='png'}
plot(cars)
```
Thanks for any advice. Please let me know if my question is still not clear.
This is my session information.
R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] knitr_1.9.4
loaded via a namespace (and not attached):
[1] digest_0.6.4 evaluate_0.5.5 formatR_1.0 htmltools_0.2.6 rmarkdown_0.5.1 stringr_0.6.2
[7] tools_3.1.3 yaml_2.1.13
This is a bug in knitr. I just fixed it in the development version (v1.9.5). The reason for the failure was that the options for the pdf device were passed to the png device.
I have written an R package for integrating with electronic medical records. I think I have correctly added the imports and dependencies in the DESCRIPTION file and documented everything via roxygen2, but on three of my functions (which are all in the same file) I get this warning when I run devtools::check("."):
* checking for missing documentation entries ... WARNING
Undocumented code objects:
'add_to_database' 'database' 'import_CPRD_data'
All user-level objects in a package should have documentation entries.
I think I have documented these in the same way as all of my other functions which are fine. Here is one of the offending functions with the roxygen2 documentation:
#' Wrapper for dbconnect
#'
#' Connects to a SQLite database or creates one if it does not already exist
#'
#' If the '.sqlite' file extension is ommited from the dbname argument it is automatically added.
#'
#' #export
#'
#' #param dbname character name path to database file
#' #return SQLiteConnection object
#' #examples \dontrun{
#' db <- database("mydb")
#' }
database <- function(dbname){
if(!str_detect(dbname, "\\.sqlite$")) {
dbname <- paste(dbname, "sqlite", sep = ".")
}
dbConnect(SQLite(), dbname)
}
How can I get rid of this error? I have added stringr and RSQLite to the depends section of the DESCRIPTION file and they show up in NAMESPACE, so I don't think this is an import problem - but then what am I failing to document? The full package is here and the file with the file with the offending functions is here. I have looked in the writing R extensions manual and can't find the problem - don't know if I am just going blind from looking - but I can't see what I am doing differently in these functions from the others I have written!
You use roxygen, but most likely you don't roxygenize your package on build.
Either call:
roxygen2::roxygenize('.', roclets=c('rd', 'collate', 'namespace'))
or, if you use RStudio, edit Project Options (Tools menu) and in the Build Tools tab check Generate documentation with Roxygen.
I have had a similar problem when doing an R CMD check:
Status: 1 WARNING
checking for missing documentation entries ... WARNING
Undocumented code objects:
‘build.log.output’
After removing all files step-by-step I have found the reason: The .Rbuildignore file! It contained (besides other lines) one line with
^.*\.log
The last line makes R ignoring all files containing a ".log" in its name and my function was named "build.log.output" which caused R to ignore the documentation file "build.log.output.Rd" generated by Roxygen2 when creating the package file.
Therefore R CMD check could not find the documentation in the package file!
Solution:
Improve the regular expression to ignore only real log files:
^.*\.log$
("$" means matching the end of line).
Voila :-)
EDIT:
#R Yoda solved the problem stated in my "answer": It was related to a conflict between .Rbuildignore and the function name (more precisley, the file name of the function's documentation).
Same problem here. And for me, it was related to the name of the function. When the name of the function below is load_rdata (or loadrdata), I receive the warning Undocumented code objects: 'load_rdata'. When I rename the function to load_rda, everything is fine.
I know this is half a question (why is this happening), half an answer (maybe because of the function names), but I thought it might help somebody coming across this question.
#' Load RData file.
#'
#' #param file An RData file saved via \code{\link[base]{save}}.
#' #return The object save in \code{file}.
#' #references \url{http://stackoverflow.com/a/5577647}
#' #export
load_rdata <- function(file = NULL) {
env <- new.env()
nm <- load(file, env)[1]
env[[nm]]
}
This is the output from sesssionInfo() and was reproducible when using devtools 1.12.0 and roxygen2 6.0.0 instead.
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=German_Germany.1252 LC_CTYPE=German_Germany.1252 LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C LC_TIME=German_Germany.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] devtools_1.12.0.9000 roxygen2_6.0.0.9000
loaded via a namespace (and not attached):
[1] R6_2.2.0 magrittr_1.5 tools_3.3.2 withr_1.0.2 memoise_1.0.0
[6] Rcpp_0.12.9 xml2_1.1.1 stringi_1.1.2 pkgload_0.0.0.9000 digest_0.6.12
[11] stringr_1.1.0 pkgbuild_0.0.0.9000 commonmark_1.1
I ran across the undocumented code error when I had multiple functions to export. I think you need to add #' #describeIn. Here's my example.
#' #title Colors Definition
#'
#' #description Define colors with transparency value.
#'
#' #param alpha Transparency value (0-1), default 1.
#'
#' #return hex value of the color
#'
#' #examples
#' Get_Red(0.5)
#' Get_Red()
#'
#' #export Get_Red
#' #export Get_Blue
#'
Get_Red <- function(alpha = 1) {
rgb(228 / 255, 26 / 255, 28 / 255, alpha)
}
#' #describeIn Get_Red Blue color function with transparency value.
Get_Blue <- function(alpha = 1) {
rgb(55 / 255, 126 / 255, 184 / 255, alpha)
}
I was experimenting with the toy foofactors package in Hadley Wickam's book. My data.R file included:
#' A character string
#'
"MyString"
and fbind.R had:
#' Print a string
#'
#' Returns the string MyString
#'
#' #export
#'
myString <- function() {
print(foofactors::MyString)
}
check complained that there was undocumented code and data. I fixed this by chnaging the function name to theString. So it appears that the names are not case sensitive which is odd.
After several frustrating hours, I found that I had man/ in my .Rbuildignore file. 🤦
I fixed this same error message by installing the devtools package.
In my case, I had created a new package on a new laptop and installed all the usual R packages and accessories: installr, testthat, roxygen2 and also the accessory tools like rtools and MiKteX. When building the package I got the same error message "checking for missing documentation entries ... WARNING: Undocumented code objects". But I fully resolved the problem by also installing the devtools package.
I recently updated knitr to 1.4, and since then my .Rnw files don't compile.
The document is rich (7 chapters, included with child="").
Now, in the recent knitr version I get an error message:
Quitting from lines 131-792 (/DATEN/anna/tex/CoSta/chapter1.Rnw)
Quitting from lines 817-826 (/DATEN/anna/tex/CoSta/chapter1.Rnw)
Fehler in if (eval) { :
Argument kann nicht als logischer Wert interpretiert werden
(the last two lines mean that knitr is looking for a logical and it cannot find it.
At those lines 131 and 817 two figures end. Compiling these sniplets separately will work.
I have no idea how to resolve this problem.
Thank's in advance for any hints that allow to resolve my issue.
Here is the sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=de_DE.UTF-8 LC_NUMERIC=C
[3] LC_TIME=de_DE.UTF-8 LC_COLLATE=de_DE.UTF-8
[5] LC_MONETARY=de_DE.UTF-8 LC_MESSAGES=de_DE.UTF-8
[7] LC_PAPER=C LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] tools stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] knitr_1.4
loaded via a namespace (and not attached):
[1] compiler_2.15.1 digest_0.6.3 evaluate_0.4.7 formatR_0.9
[5] stringr_0.6.2 tcltk_2.15.1
Following the suggestions of Hui, I run each chapter separately with
knit("chapter1.Rnw")
and so on. No error message occurs, and separate tex files are created. To provide more information I display part of the code.
There is a main document in which several options are set
<<options-setting,echo=FALSE>>=
showthis <- FALSE
evalthis <- FALSE
evalchapter <- TRUE
opts_chunk$set(comment=NA, fig.width=6, fig.height=4)
#
The each chapter is used via child chunks, e.g. chapter1 is called from
<<child-chapter1, child='chapter1.Rnw', eval=evalchapter>>=
#
The error message which appears when knitting the main Rnw file was given above.
The related Figure environment is as follows
\begin{figure}[ht]
\centering
<<wuerfel-simulation,echo=showthis,fig.height=5>>=
data.sample6 <- sample(1:6,repl=TRUE,100)
table(data.sample6)
barplot(table(data.sample6)/100,col=5,main="Haeufigkeiten beim Wuerfeln")
#
\caption{Visualisierung beim W"urfeln. 100 Versuche.}
\label{fig:muent-vis}
\end{figure}
This is not very advanced, but the error is still as it was given before.
The quitting from lines concerns a long text, from 131 (end of first chunk) to line 792 (beginning of the followup chunk), which is
<< zeiten, echo=showthis,eval=evalthis>>=
zeiten <- c(17,16,20,24,22,15,21,15,17,22)
max(zeiten)
mean(zeiten)
zeiten[4] <- 18; zeiten
mean(zeiten)
sum(zeiten > 20)
#
Is there a problem with correctly closing a chunk?
I now located the error and I provide a short piece of code with reproducible error message.It concerns conditional evaluation of child processes involving Sexpr:
The main file is the following
\documentclass{article}
\begin{document}
<<options-setting,echo=FALSE>>=
evalchapter <- TRUE
#
<<test,child="test-child.Rnw", eval=evalchapter>>=
#
\end{document}
The related child file 'test-child.Rnw' is
<<no-sexpr>>=
t <- 2:4
#
text \Sexpr{(t <- 2:4)}
knitting this 'as is' gives the error message from above. Removing the Sexpr in the child everything works nicely.
But, everything also works nicely, if I remove the conditioning in the call of the child file, i.e., without 'eval=evalchapter'
Since I use Sexpr quite often I would like to have a solution to this problem. As I mentioned earlier, there were no problems up to knitR Version 1.2.
This is related to a change in knitr 1.3 and mentioned in the NEWS:
added an argument options to knit_child() to set global chunk options for child documents; if a parent chunk calls a child document (via the child option), the chunk options of the parent chunk will be used as global options for the child document, e.g. for <<foo, child='bar.Rnw', fig.path='figure/foo-'>>=, the figure path prefix will be figure/foo- in bar.Rnw; see How to avoid figure filenames in child calls for an application
And this caused a bug for inline R code. In your case, the chunk option eval=evalchapter was not evaluated when it is used for evaluating inline code. I have fixed the bug in the development version v1.4.5 on Github.
I am getting the following error when checking my R package
> Error: could not find function "locdata"
> Execution halted
> when running code in ‘DFSurvey.Rnw’
> ...
>
> > opts_chunk$set(cache = TRUE, fig.path = "DFSurveyImages/", dev = "pdf")
>
> When sourcing ‘DFSurvey.R’:
> Error: object 'opts_chunk' not found
> Execution halted
Yihui Xie (knitr developer) said that was because in RStudio, knitr was not set as the method for weaving .Rnw files, https://groups.google.com/forum/?fromgroups#!topic/knitr/9672CBbc8CM. I have knitr set in both the tools and build options, in the R package DESCRIPTION file I have:
VignetteBuilder: knitr
Suggests: knitr
and in the vignette I have:
%\VignetteEngine{knitr}
%\VignetteDepends{knitr,xtable,TSP}
When I use compile the pdf in RStudio or use knit("KNITR.Rnw"), it compiles correctly. When I check the package, I get the above errors for each vignette. I even put
require(knitr)
before my opts_chunk$set statement. That did not help. I have also run the check from the command line and gotten the same error. Thank you for any help.
Knitr is a useful package. I run long simulations in vignettes, and the cache makes it possible to correct errors without running the simulations over each time. It does not have the problem of trying to find the Sweave.sty file either.
Here is my sessionInfo()
> R version 3.0.0 (2013-04-03)
> Platform: x86_64-apple-darwin10.8.0 (64-bit)
>
> locale:
> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
>
> attached base packages:
> [1] tcltk grid stats graphics grDevices utils datasets methods
> [9] base
>
> other attached packages:
> [1] DualFrame_0.5 xtable_1.7-1 TSP_1.0-7
> [4] maptools_0.8-23 lattice_0.20-15 foreign_0.8-53
> [7] spsurvey_2.5 sp_1.0-9 stringr_0.6.2
> [10] sqldf_0.4-6.4 RSQLite.extfuns_0.0.1 chron_2.3-43
> [13] gsubfn_0.6-5 proto_0.3-10 RSQLite_0.11.3
> [16] DBI_0.2-7 knitr_1.2 gpclib_1.5-5
>
> loaded via a namespace (and not attached):
> [1] deldir_0.0-22 digest_0.6.3 evaluate_0.4.3 formatR_0.7 MASS_7.3-26
> [6] rgeos_0.2-17 tools_3.0.0
put library(knitr) before this opts_chunk$set(cache = TRUE, fig.path = "DFSurveyImages/", dev = "pdf")
You have to load the knitr library first, try this:
```{r setoptions, echo=FALSE}
library(knitr)
opts_chunk$set(cache = TRUE, fig.path = "DFSurveyImages/", dev = "pdf")```
For a knitr vignette that you can compile using knit() or with the "Compile PDF" button in RStudio, but that gets an
Error: object 'opts_chunk' not found
Execution halted
error when checking or building the package, the package check code is not recognizing that your .Rnw file should be knited and not Sweaveed. Check that you have the following:
The vignettes are in the vignette directory, if you have R 3.0.0 or
higher (this was the solution to this post),
cran.r-project.org/doc/manuals/r-devel/R-exts.html#Non_002dSweave-vignettes
Include %\VignetteEngine{knitr::knitr} in the vignette metadata,
yihui.name/knitr/demo/vignette/
Specify VignetteBuilder: knitr in the package DESCRIPTION file, and
Add Suggests: knitr in DESCRIPTION if knitr is needed only for
vignettes
If that does not work add a require(knitr) statement before you set your global options in opts_chunk(), as Ben Bolker, Yuhui and Tyler Rinker suggested.
If in RStudio:
In BOTH the Build configuration and Tool options, set the Sweave option to knitr, www.rstudio.com/ide/docs/authoring/rnw_weave
Changing the Sweave option to knitr in the Tools options worked for me.
I run into this same problem today. Before it was always good. The error message was:
Quitting from lines 14-49 (report.Rmd)
Error in eval(expr, envir, enclos) : object 'opts_chunk' not found
I first specified library(knitr) right before the global options. Did not help.
I specified the name space before the opts_chunk and it worked, like knitr::opts_chunk.
I've tried to write reproducable example below. It is a mix of .Rmd and .r . Hopefully you can see why.
The problem I have is that non-english characters are treated differently depending on whether code is run directly in the console or when Knitted to HTML.
In the example below I create a small data.frame with characters ü and ö, write it to csv, then read it back in again.
If the writing and reading both take place inside or outside a chunk, then all is well.
But if the writing and reading take place in different places then a different encoding is used (I think). and characters get mixed up.
This means that when reading in data I need a different encoding when compiling an .Rmd file than when working directly in R.
As far as I can see the locale is always the same, so I don't understand what's going on.
Any ideas?
Write and read csv directly to create new datafile
df2 <- data.frame(Cäl1 = c(1,2), Col2 = c("ü","a"))
write.csv(df2, file="df2.csv")
read.csv("df2.csv")
Sys.getlocale(category = "LC_ALL")
Now try Knitting the whole document (just running the chunk behaves differently)
```{r read_inside}
read.csv("df2.csv")
Sys.getlocale(category = "LC_ALL")
```
this second chunk will work because the data.frame is created inside the chunk
```{r write_read_inside}
df2 <- data.frame(Cäl1 = c(1,2), Col2 = c("ü","a"))
write.csv(df2, file="df2.csv")
read.csv("df2.csv")
Sys.getlocale(category = "LC_ALL")
```
Session Info:
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252 LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] tools_2.15.0
So the answer is to guarantee UTF8 encoding, e.g. write.csv(..., fileEncoding = 'UTF-8'). The root problem was actually that RStudio uses UTF8 by default, but R uses the native encoding of the OS by default. We can either ask R to use UTF8 in write.csv, or ask RStudio to use native encoding (options(encoding = 'native.enc')).