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.
Related
Using the distill package and Rmarkdown for writing a blog, when rendering the .Rmd file I get errors when code chunks include data.table := and ., but not functions such as data.table(). The errors occur when the YAML header states draft: false but not when draft: true.
The R code chunk in the .Rmd file:
# create a data.table
library(data.table)
DT <- data.table(p = 1:5, q = 6:10)
# operate with ":="
DT[, r := p + q][]
# operate with "."
DT[, .(p)]
With draft: true in the YAML header, the .Rmd file knits with no problem.
With draft: false, I can still run the R code chunks with no error but knitting the .Rmd file produces this error:
Error: Check that is.data.table(DT) == TRUE. Otherwise, :=, `:=`(...)
and let(...) are defined for use in j, once only and in particular
ways. See help(":=").
Execution halted
If I comment out the line with the := operation, knitting the document produces a similar error on the . operation:
Error in .(p) : could not find function "."
Calls: <Anonymous> ... withVisible -> eval -> eval -> [ ->
[.data.table -> [.data.frame
Execution halted
On Stackoverflow I found a similar issue 3 years ago with the rtvs package (RTVS: Unable to Knit Document with data.table) that suggested a workaround using assignInNamespace(). I copied the suggestion to my code chunk and changed “rtvs” to “distill”, as follows:
# workaround
assignInNamespace("cedta.pkgEvalsUserCode",
c(data.table:::cedta.pkgEvalsUserCode, "distill"),
"data.table")
The help page for assignInNamespace() says the function is intended for use within a package, which my blog is not, but it does solve my problem. Adding this workaround to the first code chunk eliminates the errors and the .Rmd file renders correctly.
My questions are:
Does using assignInNamespace() in this way produce any problematic side effects?
Is there another solution or is this possibly a case where data.table or distill might need a patch?
Session information
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)
Matrix products: default
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] data.table_1.14.3
loaded via a namespace (and not attached):
[1] fansi_1.0.2 digest_0.6.29 R6_2.5.1 jsonlite_1.7.3
[5] magrittr_2.0.2 evaluate_0.14 stringi_1.7.6 rlang_1.0.1
[9] cachem_1.0.6 cli_3.2.0 rstudioapi_0.13 jquerylib_0.1.4
[13] bslib_0.3.1 vctrs_0.3.8 rmarkdown_2.11 distill_1.3
[17] tools_4.1.2 stringr_1.4.0 xfun_0.29 yaml_2.2.2
[21] fastmap_1.1.0 compiler_4.1.2 memoise_2.0.1 htmltools_0.5.2
[25] knitr_1.37 downlit_0.4.0 sass_0.4.0
2022-06-06 Update.
I've switched blog-authoring software from distill to quarto. The problem described above does not occur with quarto and porting older posts to quarto has been fairly straightforward.
I'm using bookdown to generate notes for an R. A minimal bookdown example that exhibits the error:
https://github.com/DavisBrian/bookdown_error
Everything worked great until I tried to add a plot (dataviz.Rmd). When building the book I get the following error:
! LaTeX Error: File `dataviz_files/figure-latex/plotxyx-1' not found.
Error: Failed to compile rclassnotes.tex. See rclassnotes.log for more info.
In addition: Warning message:
In parse_packages(logfile, quiet = c(TRUE, FALSE, FALSE)) :
Failed to find a package that contains dataviz_files/figure-latex/plotxyx-1
Execution halted
Exited with status 1.
I've run this under:
> sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.4
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
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] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] compiler_3.4.4 backports_1.1.2 bookdown_0.7 magrittr_1.5 rprojroot_1.3-2 htmltools_0.3.6 tools_3.4.4
[8] yaml_2.1.18 Rcpp_0.12.16 stringi_1.1.7 rmarkdown_1.9 knitr_1.20 xfun_0.1 stringr_1.3.0
[15] digest_0.6.15 evaluate_0.10.1
Any ideas on where to go from here?
Edit:
It seems very similar to:
https://github.com/rstudio/bookdown-demo/issues/3
and
https://github.com/rstudio/bookdown/issues/342
Note I have this issue with both Windows and Mac OSX. I don't think it's a simple software installation error of one of the components.
The files seem to be created in _bookdown_files/dataviz_files/figure-latex/ and temporarily in _dataviz_files/figure-latex/
The problem was due to the fact that you set the graphical device to svg in _common.R: https://github.com/DavisBrian/bookdown_error/blob/9f4078a/_common.R#L13
knitr::opts_chunk$set(
comment = "#>",
collapse = TRUE,
cache = FALSE,
out.width = "70%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold",
dev = "svg"
)
LaTeX does not support SVG images natively (at least for now). You have to either use special LaTeX packages, or use an image format that LaTeX can recognize, such as pdf or png.
When using R Studio, I usually just work with an .R file stacked on top of the Console. I keep the other panes (Environment, History, Files, etc) hidden.
But whenever I plot a graph, the other panes automatically pop out of the side bar to show me the Plot pane. Because I work on a laptop, this makes everything too small to see. By clicking the Zoom button on the Plots pane, I can get the plot also show up in a new window, but does not prevent the Plots pane from showing up.
Is there a way to "disable" the Plots pane in R Studio, and force plots show up in a new window?
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
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
[5] datasets methods base
other attached packages:
[1] ggplot2_2.2.1 jsonlite_1.4
[3] data.table_1.10.4
loaded via a namespace (and not attached):
[1] labeling_0.3 colorspace_1.2-6
[3] scales_0.4.1 lazyeval_0.2.0
[5] plyr_1.8.4 tools_3.2.3
[7] gtable_0.1.2 tibble_1.3.0
[9] curl_2.5 Rcpp_0.12.10
[11] grid_3.2.3 munsell_0.4.2
>
The dev.new() function will open a new plot window, which then becomes the target for all plots.
If you wish to open another window you can run the command a second time to open a second window.
dev.off() will shut down the window (in the order they were opened by default).
You can see how to control multiple graphics devices in the documentation here.
In RStudio, the default graphics device is normally "RStudioGD". You can change that to something else: the normal choices are "windows" on Windows, "quartz" on MacOS, "X11" on Linux. So for example, use
options(device = "quartz")
in your RStudio session on a Mac and you'll get the regular MacOS graphics window.
Try using the windows command before your plot call.
windows();(mpg ~ wt, mtcars)
The plot should pop-up in its own window whilst the pane stays minimized.
Commenting the following lines in C:\Program Files\RStudio\R\Tools.R seems to work (it may be necessary to edit the file as administrator):
# set our graphics device as the default and cause it to be created/set
.rs.addFunction( "initGraphicsDevice", function()
{
# options(device="RStudioGD")
# grDevices::deviceIsInteractive("RStudioGD")
grDevices::deviceIsInteractive()
})
If you want all plots in the current script to appear on a separate window, this should do the job:
dev.new(noRStudioGD = TRUE)
*Tested on RStudio version 1.4.1106 for Windows with R version 4.0.5 (2021-03-31)
For a 'permanent' solution, the answer by Rubén Fernández-Casal should work well.
You can force RStudio to show plots in the Source window if you use R Markdown. In a Rmd file, plots are shown together with code; it's called an R Markdown notebook. You can set the size of the plots too, in what is called an R code chunk:
```{r fig.height = 2, fig.width = 3}
plot(mpg ~ wt, mtcars)
```
When you run the chunk, the plot is shown below it.
If you want to set the plot size for the whole notebook, set the package option using opts_knit and opts_chunk, for example:
```{r setup}
library(knitr)
opts_knit$set(global.par = TRUE)
opts_chunk$set(fig.width = 4.5, fig.height = 3.5)
```
For more information, see here and here.
While using the Boot function from the car package I get the error message
Error in get(".y.boot", envir = .carEnv) : object '.carEnv' not found
I suspect I have inadvertently changed/set something in my OS and have no idea what it might be. Running the code below returns an error on my desktop but runs without error on a laptop running the same OS (Yosemite) as well as a desktop running Windows 7 (all using R-3.1.2). The code that triggers the message is
library(car)
swiss.lm <- lm(Fertility ~ Education, data = swiss)
BC <- Boot(swiss.lm, R = 999, method = "case") # No Problems
BR <- Boot(swiss.lm, R = 999, method = "residual") # Problems now
Error in get(".y.boot", envir = .carEnv) : object '.carEnv' not found
I have reinstalled R but the error still appears when running the above code. Any suggestions as to what I have done and how to get the code to run and find the environment would be most appreciated. TIA!
> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-apple-darwin13.4.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] stats graphics grDevices utils datasets methods base
other attached packages:
[1] car_2.0-24
loaded via a namespace (and not attached):
[1] boot_1.3-15 grid_3.1.2 lattice_0.20-29 lme4_1.1-7 MASS_7.3- 37 Matrix_1.1-5
[7] mgcv_1.8-4 minqa_1.2.4 nlme_3.1-119 nloptr_1.0.4 nnet_7.3-9 parallel_3.1.2
[13] pbkrtest_0.4-2 quantreg_5.11 Rcpp_0.11.4 SparseM_1.6 splines_3.1.2 tools_3.1.2
Looks like a reproducible bug in a car package. According to package news the changes in latest version (2.0-24) are related to .carEnv handling.
I tried to get around the issue by simply assigning the .carEnv before call to Boot with
.carEnv <- car:::.carEnv
This makes the Boot function execute without errors, but I am not sure of any other effects.
The package maintainer emailed me and indicated a bug had been introduced in 2.0-24 and that he would attempt to fix the bug.
I am using the ggmap library in R to produce a map of the Atlanta area. When running the code, I'm able to get points plotted on the map as well as other layers, but am not able to get the map itself to print in any graphics device other than PDF. I suspect a configuration issue as I'm able to use this code on a different computer without issue, but two other machines simply display blank plots.
Here is a scaled down version of the code. I am assuming that my blank plots won't be reproducible, but I'm hoping to get some guidance on where the configuration problem might be.
library('ggplot2')
library('ggmap')
library('mapproj')
# ggmapTemp.png gets saved to the working directory correctly
atlanta <- get_map(location=c(lon=-84.26039,
lat=33.8751),
zoom=9,maptype='roadmap')
atlantaMap <- ggmap(atlanta, extent = 'device', legend = 'topleft')
# this produces a blank plot from both RStudio as well as R
atlantaMap
# this produces the actual map correctly
pdf("plot.pdf")
atlantaMap
dev.off()
# this produces a png file with only a white background
png("plot.png")
atlantaMap
dev.off()
Session Info:
R version 2.15.3 (2013-03-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] mapproj_1.2-1 ggmap_2.3 ggplot2_0.9.3.1 maps_2.3-6 maptools_0.8-27
[6] sp_1.0-14 car_2.0-19 reshape2_1.2.2 plyr_1.8 Revobase_6.2.0
[11] RevoMods_6.2.0 RevoScaleR_6.2.0 lattice_0.20-13 rpart_4.1-0
loaded via a namespace (and not attached):
[1] codetools_0.2-8 colorspace_1.2-4 dichromat_2.0-0 digest_0.6.3 foreach_1.4.0
[6] foreign_0.8-52 grid_2.15.3 gtable_0.1.2 iterators_1.0.6 labeling_0.2
[11] MASS_7.3-23 munsell_0.4.2 nnet_7.3-5 png_0.1-6 proto_0.3-10
[16] RColorBrewer_1.0-5 RgoogleMaps_1.2.0.5 rjson_0.2.13 RJSONIO_1.0-3 scales_0.2.3
[21] stringr_0.6.2 tools_2.15.3
And capabilities:
jpeg png tiff tcltk X11 aqua http/ftp sockets libxml fifo cledit
TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE
iconv NLS profmem cairo
TRUE TRUE TRUE TRUE
The problem has to do with the server limiting the bit depth that gets passed through the connection. Oracle documents the problem and solution on their site:
In a Remote Desktop session, all environment variables, including display variables determining Color Depth, are determined by the RCP-Tcp connection settings. For example, users can reduce the Color Depth when connecting over a slow connection. The different settings are 15 bits, 16 bits, 24 bits, or 32 bits per pixel. To raise the Remote Desktop color depth:
On the Windows server, launch Remote Desktop Session Host Configuration from the Accessories menu.
Under Connections, right click on RDP-Tcp and select Properties.
On the Client Settings tab either uncheck LimitMaximum Color Depth or set it to 32 bits per pixel.
Upon unchecking the "Limit Maximum Color Depth" check box and reconnecting to the server, the raster map backgrounds now show up as expected. Note that they also provide option 2 which is to output to an alternate device.
It seems jrshrenk haven't updated R and the packages in a while. Although in theory your versions of R, ggmap, png and ggplot2 seems sufficient:
Package: ggmap
Version: 2.4
Depends: R (>= 2.14.0), ggplot2 (>= 0.9.2)
Imports: proto, scales, RgoogleMaps, png, plyr, reshape2, grid, rjson,
mapproj, jpeg, geosphere, digest
Suggests: MASS, stringr
License: GPL-2
NeedsCompilation: no
Package: png
Version: 0.1-7
Depends: R (>= 2.9.0)
License: GPL-2 | GPL-3
NeedsCompilation: yes
I would just try to update R and the packages to see if it solves the issue:
#Save your current packages but not the base ones:
savepackages <- rownames(installed.packages(priority='NA'))
write(savepackages, file="listpackages.txt")
#Check for Updates of R
library(installr)
check.for.updates.R(notify_user = TRUE, use_GUI = TRUE,
page_with_download_url = "http://cran.rstudio.com/bin/windows/base/",
pat = "R-[0-9.]+-win")
#Download and Install New Version
install.R(page_with_download_url = "http://cran.rstudio.com/bin/windows/base/",
pat = "R-[0-9.]+-win.exe", to_checkMD5sums = TRUE,
keep_install_file = TRUE, download_dir = tempdir(), silent = FALSE)
#Then reinstall packages
pkg.ls <- read.table("listpackages.txt")
install.packages(pkg.ls)