Knitr providing different results than RStudio - r

I'm doing some initial text mining using 'tm' and 'RWeka' using Knitr for reproducibility.
I'm trying to obtain a term-document matrix for a corpus based on two text files, and the process has different results when I run the code in RStudio and when I knit it into a HTML file:
... when I try other document outputs PDF and Word outputs:
agree with RStudio.
And, I need an HTML output....
Any idea of what may be going on?
Here it is the .Rmd code
---
title: "test"
author: "me"
output: word_document
---
```{r init, echo=FALSE, warning=FALSE, cache=TRUE, message=FALSE}
library(knitr)
library(tm)
library(SnowballC)
library(RWeka)
setwd("~")
options(mc.cores=1) # some problems with parallel processing
```
```{r 1-gram-test, echo=FALSE, eval=TRUE,cache=TRUE}
doc1 <- c("en un lugar de la mancha de cuyo nombre no quiero acordarme habitaba un hidalgo de los de adarga antigual, rocín flaco y galgo corredor")
doc2 <- c("había una vez un barquito chiquitito, que no sabía, que no sabía, que no sabía navegar... pasaron un dos tres cuatro cinco seis semanas y el barquito navegó.")
docs <- c(doc1, doc2)
es <- Corpus(VectorSource(docs),
readerControl = list(reader = readPlain,
language = "ES-es", load = TRUE))
es
# convert to plain text
es1 <- tm_map(es, PlainTextDocument)
monogramtok <- function(x) {
RWeka::NGramTokenizer(x, RWeka::Weka_control(min = 1, max = 1))
}
es_tdm1 <- TermDocumentMatrix(es1)
esmono_tdm1 <- TermDocumentMatrix(es1,
control = list(tokenize = monogramtok,
wordLengths = c(1, Inf))) #,
printf("es_tdm1")
es_tdm1
printf("esmono_tdm1")
esmono_tdm1
```
sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.4 (El Capitan)
locale:
[3] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[3] stats graphics grDevices utils datasets methods base
other attached packages:
[3] R.utils_2.2.0 R.oo_1.20.0 R.methodsS3_1.7.1 dplyr_0.4.3 xtable_1.8-0
[6] pander_0.6.0 RWeka_0.4-24 SnowballC_0.5.1 tm_0.6-2 NLP_0.1-9
[11] knitr_1.12.3

I had a similar problem, then realized I was caching my knitr chunks with the option cache=TRUE (as you seem to have set as well).
This can cause some really subtle errors if the cached chunks have side effects or depend on external resources.
When I disabled caching, my reproducibility issues disappeared.

Related

knitr bookdown::gitbook and webgl: rotation does not work properly

I have the following Rmd file:
---
output: bookdown::gitbook
---
```{r include=FALSE}
rgl::setupKnitr()
```
```{r testing1,webgl=TRUE}
with(attitude,
car::scatter3d(x = rating, z = complaints, y = learning)
)
```
```{r testing2,webgl=TRUE}
with(attitude,
car::scatter3d(x = rating, z = complaints, y = learning)
)
```
When I knit this file, it produces and HTML file containing two, identical 3D interactive scatterplots. Both scatterplots look like they should, but the second scatterplot does not rotate properly. It will not rotate horizontally in depth correctly (eg, around the vertical axis).
In case it helps, you can find the HTML output of the knit here: https://www.dropbox.com/s/v3usmtes7n54t6q/Untitled.html.zip?dl=0
I have done all the following, none of which have fixed the problem:
Updated all packages with update.packages().
Installed the development version of bookdown.
Installed the development version of knitr.
Tried the solution here (didn't work): interactive 3D plots in markdown file - not working anymore?
I have noted the following:
If I change the output to html_document I do not have the problem (I'm debugging the problem in a bookdown::gitbook though, so that knowledge does not directly help me).
In the Firefox (77.0.1, 64-bit) javascript error console there is an error: TypeError: li[0] is undefined / plugin-bookdown.js:152:43 (which appears to have something to do with the table of contents and scrolling?)
Here is the output of sessionInfo():
> sessionInfo()
R version 4.0.0 (2020-04-24)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.5
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] bookdown_0.19.4 fansi_0.4.1 digest_0.6.25 crayon_1.3.4
[5] assertthat_0.2.1 evaluate_0.14 rlang_0.4.6 cli_2.0.2
[9] rstudioapi_0.11 rmarkdown_2.3 tools_4.0.0 glue_1.4.1
[13] xfun_0.14 yaml_2.2.1 rsconnect_0.8.16 compiler_4.0.0
[17] htmltools_0.5.0 knitr_1.28.7
In addition, here are the versions of some other relevant packages:
> installed.packages()[c("rgl","mgcv","car"),"Version"]
rgl mgcv car
"0.100.54" "1.8-31" "3.0-8"
Edit to add more detail
I have the same problem while using rgl::persp3d, so it isn't specific to car::scatter3d. The HTML from the Rmd file below uses only rgl but exhibits the same behavior.
---
output: bookdown::gitbook
---
```{r include=FALSE}
rgl::setupKnitr()
x <- seq(-10, 10, length = 30)
y <- x
f <- function(x, y) { r <- sqrt(x^2 + y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
```
```{r testing1,webgl=TRUE}
rgl::persp3d(x, y, z, aspect = c(1, 1, 0.5), col = "lightblue",
xlab = "X", ylab = "Y", zlab = "Sinc( r )",
polygon_offset = 1)
```
```{r testing2,webgl=TRUE}
rgl::persp3d(x, y, z, aspect = c(1, 1, 0.5), col = "lightblue",
xlab = "X", ylab = "Y", zlab = "Sinc( r )",
polygon_offset = 1)
```
This turned out to be a bug in rgl, that was using an obsolete method to compute the location of mouse clicks relative to objects in scenes. It worked in an html_document, but not with bookdown::gitbook.
The development version (0.102.6) of rgl has fixed this, but it contains some really major changes, and a few other things are still broken by them: in particular using the webgl=TRUE chunk option. If you want to use the devel version, you should use explicit calls to rglwidget() in each chunk, or if you want to try out the new stuff, use rgl::setupKnitr(autoprint = TRUE) and just treat rgl graphics like base graphics, controlled by chunk options fig.keep etc.
Edited to add: version 0.102.7 fixes the known webgl=TRUE issue.

Looping through data with Rmd input file with flextable results in pandoc version error - but works fine without the loop?

I'm trying to generate lots of word documents with a loop and RMarkdown. I'm using flextable to make the tables with the acceptable formatting for the report. Everything works fine until I try to loop through a dataset. Then I get an error about the pandoc version:
Error in knit_print.flextable(x, ...) : pandoc
version >= 2.0 required for flextable rendering in docx "
However, It looks like I download version 2.1 on January 19th...
pandoc_version()
[1] ‘1.19.2.1’
Not to mention, it runs fine without the loop when I just run it in the rmd file. (I would think it wouldn't run either way if the version wasn't correct).
I also tried sys.setenv()
Sys.setenv("RSTUDIO_PANDOC" = "PATH TO PANDOC BIN")
But still, it works for the Rmd file alone, but I get the same error about the version when I try to loop it. Again, I feel like this wouldn't work in the rmd file if this wasn't correct.
I'm including a reproducible example below. If I can provide any other information please let me know. Thanks!
My loop/R Script
DAT<-dplyr::sample_n(iris, 10)
Sys.setenv("RSTUDIO_PANDOC" = "PATH TO PANDOC BIN")
for (i in 1:nrow(DAT)){
rmarkdown::render(input = "Loop Testing R Markdown.Rmd",
output_format = "word_document",
output_file = paste("Documents", i, ".docx", sep=''),
output_dir = "Documents/")
}
> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
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] rmarkdown_1.8 knitr_1.17 bindrcpp_0.2 dplyr_0.7.4
qsurvey_0.0.3 installr_0.19.0
[7] stringr_1.2.0 officer_0.2.1 flextable_0.4.2 pander_0.6.1
kableExtra_0.7.0
loaded via a namespace (and not attached):
[1] zip_1.0.0 Rcpp_0.12.14 bindr_0.1
pillar_1.0.1 compiler_3.4.3
[6] plyr_1.8.4 highr_0.6 R.methodsS3_1.7.1
R.utils_2.6.0 base64enc_0.1-3
[11] tools_3.4.3 digest_0.6.13 uuid_0.1-2 lubridate_1.7.1 jsonlite_1.5
[16] evaluate_0.10.1 tibble_1.4.1 viridisLite_0.2.0 pkgconfig_2.0.1 rlang_0.1.6
[21] shiny_1.0.5 curl_3.1 yaml_2.1.16 httr_1.3.1 xml2_1.1.1
[26] htmlwidgets_0.9 gdtools_0.1.6 hms_0.4.0 DT_0.2 rprojroot_1.3-1
[31] glue_1.2.0 data.table_1.10.4-3 R6_2.2.2 readr_1.1.1 magrittr_1.5
[36] backports_1.1.2 scales_0.5.0 htmltools_0.3.6 assertthat_0.2.0 rvest_0.3.2
[41] xtable_1.8-2 mime_0.5 colorspace_1.3-2 httpuv_1.3.5 stringi_1.1.6
[46] visNetwork_2.0.2 munsell_0.4.3 R.oo_1.21.0
> pandoc_version()
[1] ‘1.19.2.1’
>
The Rmd File to Reference
---
output:
word_document:
reference_docx: mystyles.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r results='asis', include=FALSE}
## Load Packages
library(knitr)
library(rmarkdown)
library(dplyr)
```
```{r results="asis"}
#DAT<-iris # I comment this out when I run the loop, but leave it in when testing the format.
library(pander)
panderOptions('knitr.auto.asis', FALSE)
First_N<-DAT[[i,1]]
Last_N<-DAT[[i,2]]
Name<-c(First_N, " ", Last_N)
Name<-paste(Name, collapse = "")
cat("# ", Name, "\n")
```
## Title of Report Section
```{r, demo1, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
DemoTbl_1<-matrix(nrow = 2, ncol = 4)
DemoTbl_1[[1,1]]<- "Name:"
DemoTbl_1[[1,2]]<- Name
DemoTbl_1[[1,3]]<- "State:"
DemoTbl_1[[1,4]]<-DAT[[i,3]]
DemoTbl_1[[2,1]]<- "Other Feild Title:"
DemoTbl_1[[2,2]]<-DAT[[i,4]]
DemoTbl_1[[2,4]]<-DAT[[i,5]]
DemoTbl_1[[2,3]]<- "Pther Feild Title"
library("flextable")
library("officer")
myft<-regulartable(as.data.frame(DemoTbl_1))
myft <- bg(myft, bg = "#000000", j=1)
myft <- color(myft, color = "#ffffff", j=1)
myft <- border(myft, border = fp_border(color = "#000000"), part = "all")
myft <- align( myft, align = "center", part = "all" )
myft <- width(myft, width = 1.5, j=1)
myft <- width(myft, width = 3, j=2)
myft <- width(myft, width = 1.5, j=3)
myft <- width(myft, width = 1.25, j=4)
myft<- delete_part(myft, part = "header")
myft <- bg(myft, bg = "#000000", j=3)
myft <- color(myft, color = "#ffffff", j=3)
```
```{r, results='asis', echo=FALSE}
#DemoTbl_1 # This prints fine
myft ## This seems to be giving me the error "uitting from lines 77-78
(Loop_Testing_R_Markdown.Rmd) Error in knit_print.flextable(x, ...) : pandoc
version >= 2.0 required for flextable rendering in docx "
```
**Also - In case it's helpful, here is the traceback: **
Error in knit_print.flextable(x, ...) :
pandoc version >= 2.0 required for flextable rendering in docx
20. stop("pandoc version >= 2.0 required for flextable rendering in docx")
19. knit_print.flextable(x, ...)
18. knit_print(x, ...)
17. withVisible(knit_print(x, ...))
16. fun(x, options = options)
15. value_fun(ev$value, ev$visible)
14. withVisible(value_fun(ev$value, ev$visible))
13 .withCallingHandlers(withVisible(value_fun(ev$value, ev$visible)),
warning = wHandler, error = eHandler, message = mHandler)
12. handle(pv <- withCallingHandlers(withVisible(value_fun(ev$value,
ev$visible)), warning = wHandler, error = eHandler, message = mHandler))
11. evaluate_call(expr, parsed$src[[i]], envir = envir, enclos = enclos,
debug = debug, last = i == length(out), use_try = stop_on_error !=
2L, keep_warning = keep_warning, keep_message = keep_message,
output_handler = output_handler, include_timing = include_timing)
10. evaluate(code, envir = env, new_device = FALSE, keep_warning = !isFALSE(options$warning),
keep_message = !isFALSE(options$message), stop_on_error = if (options$error &&
options$include) 0L else 2L, output_handler = knit_handlers(options$render,
options))
9. in_dir(input_dir(), evaluate(code, envir = env, new_device = FALSE,
keep_warning = !isFALSE(options$warning), keep_message = !isFALSE(options$message),
stop_on_error = if (options$error && options$include) 0L else 2L,
output_handler = knit_handlers(options$render, options)))
8. block_exec(params)
7. call_block(x)
6. process_group.block(group)
5. process_group(group)
4. withCallingHandlers(if (tangle) process_tangle(group) else process_group(group),
error = function(e) {
setwd(wd)
cat(res, sep = "\n", file = output %n% "") ...
3. process_file(text, output)
2. knitr::knit(knit_input, knit_output, envir = envir, quiet = quiet,
encoding = encoding)
1. rmarkdown::render(input = "Loop Testing R Markdown.Rmd", output_format = "word_document",
output_file = paste("Documents", i, ".docx", sep = ""), output_dir = "Documents/")
You need to create a file .Rprofile at the root of your R project (see ?Startup). In that file add your R instruction to set pandoc path (Sys.setenv("RSTUDIO_PANDOC" = "PATH TO PANDOC BIN")).
rmarkdown::render is using a new R session and your variable is not set when rendering.

How to solve compatibility problems mgcv ang gam packages?

I'm compiling using RMarkdown and knitr a short protocol for me (in one html file), about modelling. The basis is Zuur, A. F. "leno, E. N, Walker, NJ, Saveliev, AA & Smith, G M. 2009: Mixed effects models and extensions in ecology with R."
I downloaded the code and the datasets shared in their website1 and I'm mixing it with other sources and comments to produce something useful for me. In this website you can freely download the two dataset I'm using.
The main problem is that I'm trying to mix something made with mgcv package and something with gam package.
I clearly understood from this two topics that this is the problem:
R Package conflict between gam and mgcv?
Are there known compatibility issues with R package mgcv? Are there general rules for compatibility?
But I would like to find a solution. Obviously as answered in theese two topics specify the package or detach the unused one does not work. I just tried in my code.
Those are the parts that are causing me problems:
---
title: "error"
author: "Simone Marini"
date: "29 marzo 2016"
output: html_document
---
```{r setup, include = FALSE, cache = FALSE}
knitr::opts_chunk$set(error = TRUE) # to allow rendering to html even if there are errors
```
```{r}
Loyn <- read.table(file = "zuur_data/Loyn.txt", header = TRUE, dec = ".")
Loyn$fGRAZE <- factor(Loyn$GRAZE) # Transform in factor Graze data (from 1 to 5 -> 5 classes)
Loyn$L.AREA<-log10(Loyn$AREA)
Loyn$L.DIST<-log10(Loyn$DIST)
Loyn$L.LDIST<-log10(Loyn$LDIST)
```
```{r}
library(mgcv)
AM1<-mgcv::gam(ABUND~s(L.AREA)+s(L.DIST)+s(L.LDIST)+
s(YR.ISOL)+s(ALT)+fGRAZE, data = Loyn)
# The anova command does not apply a sequential F-test as it did for the linear regression model.
# Instead, it gives the Wald test (approximate!) that shows the significance of each term in the model.
anova(AM1)
AM2<-mgcv:::gam(ABUND ~ s(L.AREA, bs = "cs") + s(L.DIST, bs = "cs") +
s(L.LDIST,bs = "cs") + s(YR.ISOL, bs = "cs") +
s(ALT, bs = "cs") + fGRAZE, data = Loyn)
anova(AM2)
AM3 <- mgcv:::gam(ABUND ~ s(L.AREA, bs = "cs") + fGRAZE, data = Loyn)
#Model plot
plot(AM3)
E.AM3 <- resid(AM3) # Residuals
Fit.AM3 <- fitted(AM3) # Fitted values
plot(x = Fit.AM3, y = E.AM3, xlab = "Fitted values",
ylab = "Residuals") # Graph
M3<-lm(ABUND ~ L.AREA + fGRAZE, data = Loyn)
AM3<-mgcv:::gam(ABUND ~ s(L.AREA, bs = "cs") + fGRAZE, data = Loyn)
anova(M3, AM3)
```
```{r}
rm(list=ls())
detach("package:mgcv")
ISIT <- read.table(file = "zuur_data/ISIT.txt", header = TRUE, dec = ".")
ISIT$fStation<-factor(ISIT$Station)
op <- par(mfrow=c(2,2),mar=c(5,4,1,2))
Sources16<-ISIT$Sources[ISIT$Station==16]
Depth16<-ISIT$SampleDepth[ISIT$Station==16]
plot(Depth16,Sources16,type="p")
library(gam)
M2<-gam:::gam(Sources16~gam::lo(Depth16,span=0.5))
plot(M2,se=T)
P2 <- predict(M2, se = TRUE)
plot(Depth16, Sources16, type = "p")
I1 <- order(Depth16)
lines(Depth16[I1], P2$fit[I1], lty = 1)
lines(Depth16[I1], P2$fit[I1] + 2 * P2$se[I1], lty = 2)
lines(Depth16[I1], P2$fit[I1] - 2 * P2$se[I1], lty = 2)
par(op)
```
Does anyone knows a way to "detach" completely mgcv or gam? Or a code that can "reaload" the entire environment when I have to compile the gam part?
My sessionInfo if it is useful.
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=Italian_Italy.1252 LC_CTYPE=Italian_Italy.1252 LC_MONETARY=Italian_Italy.1252
[4] LC_NUMERIC=C LC_TIME=Italian_Italy.1252
attached base packages:
[1] splines stats graphics grDevices utils datasets methods base
other attached packages:
[1] lattice_0.20-33 gam_1.12 foreach_1.4.3 mgcv_1.8-11 nlme_3.1-124
loaded via a namespace (and not attached):
[1] Matrix_1.2-3 htmltools_0.3 tools_3.2.3 yaml_2.1.13 codetools_0.2-14 rmarkdown_0.9.2
[7] grid_3.2.3 iterators_1.0.8 knitr_1.12.3 digest_0.6.9

R markdown presentation not displaying plots

I have Rstudio on Windows (sessionInfo() below) and am trying to build an r presentation using markdown. When I try to knit HTML or PDF it does not seem to be retaining the folder where plots should be generated from and as a result my presentations are missing plots. I have confirmed that it does work with a basic html_document though.
Does anyone have any ideas on how to resolve?
MWE (rstudio default with headers for slides)
---
title: "plottest2"
author: "AN Other"
date: "Monday, June 30, 2014"
output: html_document
---
## Area 1 ##
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
summary(cars)
```
## Area 2 ##
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
This generates using the knit html command, but change html_document to ioslides_presentation and it won't pick up the plot
SessionInfo
> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252 LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] lattice_0.20-29 ggplot2_1.0.0
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 digest_0.6.4 evaluate_0.5.5 formatR_0.10 grid_3.1.0 gtable_0.1.2 htmltools_0.2.4 knitr_1.6 labeling_0.2 MASS_7.3-31
[11] munsell_0.4.2 plyr_1.8.1 proto_0.3-10 Rcpp_0.11.2 reshape2_1.4 rmarkdown_0.2.49 scales_0.2.4 stringr_0.6.2 tools_3.1.0 yaml_2.1.13
C:\Program Files\R\R-3.1.0\library\base\R.Rprofile
### This is the system Rprofile file. It is always run on startup.
### Additional commands can be placed in site or user Rprofile files
#
# Copyright (C) 1995-2012 The R Core Team
### (see ?Rprofile).
### Notice that it is a bad idea to use this file as a template for
### personal startup files, since things will be executed twice and in
### the wrong environment (user profiles are run in .GlobalEnv).
.GlobalEnv <- globalenv()
attach(NULL, name = "Autoloads")
.AutoloadEnv <- as.environment(2)
assign(".Autoloaded", NULL, envir = .AutoloadEnv)
T <- TRUE
F <- FALSE
R.version <- structure(R.Version(), class = "simple.list")
version <- R.version # for S compatibility
## for backwards compatibility only
R.version.string <- R.version$version.string
## NOTA BENE: options() for non-base package functionality are in places like
## --------- ../utils/R/zzz.R
options(keep.source = interactive())
options(warn = 0)
# options(repos = c(CRAN="#CRAN#"))
# options(BIOC = "http://www.bioconductor.org")
options(timeout = 60)
options(encoding = "native.enc")
options(show.error.messages = TRUE)
## keep in sync with PrintDefaults() in ../../main/print.c :
options(scipen = 0)
options(max.print = 99999)# max. #{entries} in internal printMatrix()
options(add.smooth = TRUE)# currently only used in 'plot.lm'
options(stringsAsFactors = TRUE)
if(!interactive() && is.null(getOption("showErrorCalls")))
options(showErrorCalls = TRUE)
local({dp <- Sys.getenv("R_DEFAULT_PACKAGES")
if(identical(dp, "")) # marginally faster to do methods last
dp <- c("datasets", "utils", "grDevices", "graphics",
"stats", "methods")
else if(identical(dp, "NULL")) dp <- character(0)
else dp <- strsplit(dp, ",")[[1]]
dp <- sub("[[:blank:]]*([[:alnum:]]+)", "\\1", dp) # strip whitespace
options(defaultPackages = dp)
})
## Expand R_LIBS_* environment variables.
Sys.setenv(R_LIBS_SITE =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_SITE")))
Sys.setenv(R_LIBS_USER =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_USER")))
.First.sys <- function()
{
for(pkg in getOption("defaultPackages")) {
res <- require(pkg, quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning(gettextf('package %s in options("defaultPackages") was not found', sQuote(pkg)),
call.=FALSE, domain = NA)
}
}
.OptRequireMethods <- function()
{
if("methods" %in% getOption("defaultPackages")) {
res <- require("methods", quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning('package "methods" in options("defaultPackages") was not found', call.=FALSE)
}
}
if(nzchar(Sys.getenv("R_BATCH"))) {
.Last.sys <- function()
{
cat("> proc.time()\n")
print(proc.time())
}
## avoid passing on to spawned R processes
## A system has been reported without Sys.unsetenv, so try this
try(Sys.setenv(R_BATCH=""))
}
###-*- R -*-
## this will break if R is on a network share
.Library <- file.path(chartr("\\", "/", R.home()), "library")
.Library.site <- Sys.getenv("R_LIBS_SITE")
.Library.site <- if(!nchar(.Library.site)) file.path(R.home(), "site-library") else unlist(strsplit(.Library.site, ";"))
.Library.site <- .Library.site[file.exists(.Library.site)]
if(!nzchar(Sys.getenv("R_LIBS_USER")))
Sys.setenv(R_LIBS_USER=
file.path(Sys.getenv("R_USER"), "R",
"win-library",
paste(R.version$major,
sub("\\..*$", "", R.version$minor),
sep=".")
))
invisible(.libPaths(c(unlist(strsplit(Sys.getenv("R_LIBS"), ";")),
unlist(strsplit(Sys.getenv("R_LIBS_USER"), ";"))
)))
local({
popath <- Sys.getenv("R_TRANSLATIONS", "")
if(!nzchar(popath)) {
paths <- file.path(.libPaths(), "translations", "DESCRIPTION")
popath <- dirname(paths[file.exists(paths)][1])
}
bindtextdomain("R", popath)
bindtextdomain("R-base", popath)
bindtextdomain("RGui", popath)
assign(".popath", popath, .BaseNamespaceEnv)
})
if(nzchar(Sys.getenv("R_PAPERSIZE"))) {
options(papersize = Sys.getenv("R_PAPERSIZE"))
} else {
if(grepl("(canada|united.states)", Sys.getlocale("LC_MONETARY"),
ignore.case = TRUE)) options(papersize = "letter")
else options(papersize = "a4")
}
options(pager = if(length(grep("--ess", commandArgs()))) "console" else "internal",
useFancyQuotes = (.Platform$GUI == "Rgui"),
pdfviewer = Sys.getenv("R_PDFVIEWER", file.path(R.home("bin"), "open.exe")))
if(.Platform$GUI == "Rgui")
Sys.setenv(GFORTRAN_STDOUT_UNIT = "-1", GFORTRAN_STDERR_UNIT = "-1")
local({
br <- Sys.getenv("R_BROWSER", NA_character_)
if(!is.na(br)) options(browser = br)
tests_startup <- Sys.getenv("R_TESTS")
if(nzchar(tests_startup)) source(tests_startup)
})
C:\Program Files\R\R-3.1.0\etc\Rprofile.site
# Things you might want to change
# options(papersize="a4")
# options(editor="notepad")
# options(pager="internal")
# set the default help type
# options(help_type="text")
options(help_type="html")
# set a site library
# .Library.site <- file.path(chartr("\\", "/", R.home()), "site-library")
# set a CRAN mirror
# local({r <- getOption("repos")
# r["CRAN"] <- "http://my.local.cran"
# options(repos=r)})
# Give a fortune cookie, but only to interactive sessions
# (This would need the fortunes package to be installed.)
# if (interactive())
# fortunes::fortune()
I have found the same issue with RStudio-0.98.983 and R-3.1.1-win. Uninstalling both and reinstalling did NOT solve the issue for me. I have tried with RStudio-0.98.994 and it did not work either...
Update: This was reported (see link in the comments below) and a solution was found by the RStudio team. It seems it is an issue with the Lua base64 encoder on Windows, which is used in ioslides. The solution is to install the packages httpuv or catools. After restarting RStudio, the issue should be fixed (at least it was for me!).
I had a similar problem with a chart not being displayed. It turned out that the problem was that the name of the .Rpres file I was using had spaces in it. Once I replaced the spaces with underscores the plot appeared again.
Use "Example_File_Name.Rpres" not "Example File Name.Rpres".
I had the same problem, and a different solution worked for me.
- don't save the rmarkdown with any numbers in the document name,
- and also don't inlcude the .html in the document name, to the markdown file you wish to save
Using just a name without the two above should create one rmd-file and one html-file in your designated folder. The rmd-file will not include plots, the html-File however should inlcude them in its presentation.
This is a localised issue - an install on a fresh computer did not have this error. It could be due to having previous versions of R hanging around - suggest taking the route of completely uninstalling R and Rstudio.
Uninstalling R and Rstudio works.

R + knitr + PerformanceAnalytics plotting errors

I am running the following bit of code but for some reason when using charts.PerformanceSummary() inside a for loop it tries to make more outputs than the number of times it goes through the loop. Whereas a simple plot function seems to work fine...
Please see the .Rmd code below and then the subsequent .md file created after kniting to html...
PLOT TEST
====
```{r}
suppressPackageStartupMessages(require(PerformanceAnalytics))
for(i in 1:5){
charts.PerformanceSummary(xts(rnorm(i*1000,0.0001,0.0003),Sys.Date()-c((i*1000):1)))
}
```
```{r}
for(i in 1:5){
plot(xts(cumprod(rnorm(i*1000,0.0001,0.0003)+1),Sys.Date()-c((i*1000):1)))
}
```
Giving the following .md file
PLOT TEST
====
```r
suppressPackageStartupMessages(require(PerformanceAnalytics))
for (i in 1:5) {
charts.PerformanceSummary(xts(rnorm(i * 1000, 1e-04, 3e-04), Sys.Date() -
c((i * 1000):1)))
}
```
![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-11.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-12.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-13.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-14.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-15.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-16.png)
```r
for (i in 1:5) {
plot(xts(cumprod(rnorm(i * 1000, 1e-04, 3e-04) + 1), Sys.Date() - c((i *
1000):1)))
}
```
![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-21.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-22.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-23.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-24.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-25.png)
Notice how there are 6 output plots that the frist chunk tries to connect to but there are only 5 output plots in the second chunk despite both having the same for (i in 1:5) { bit of code...
As additional information the below was the sessionInfo
sessionInfo()
## R version 3.0.0 (2013-04-03)
## Platform: x86_64-apple-darwin10.8.0 (64-bit)
##
## locale:
## [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] PerformanceAnalytics_1.1.0 xts_0.9-3
## [3] zoo_1.7-9 knitr_1.2
##
## loaded via a namespace (and not attached):
## [1] digest_0.6.3 evaluate_0.4.3 formatR_0.7 grid_3.0.0
## [5] lattice_0.20-15 stringr_0.6.2 tools_3.0.0
EDIT
I have also just run the one line it on its own, and have a semi-fix...but not one for doing multiple charts in the same chunk...
Below is the .Rmd script together with the .md output
```{r}
charts.PerformanceSummary(xts(rnorm(1000,0.0001,0.0003),Sys.Date()-c((1000):1)))
```
```{r fig.keep='last'}
charts.PerformanceSummary(xts(rnorm(1000,0.0001,0.0003),Sys.Date()-c((1000):1)))
```
the .md output
```r
charts.PerformanceSummary(xts(rnorm(1000, 1e-04, 3e-04), Sys.Date() - c((1000):1)))
```
![plot of chunk unnamed-chunk-4](figure/unnamed-chunk-41.png) ![plot of chunk unnamed-chunk-4](figure/unnamed-chunk-42.png)
```r
charts.PerformanceSummary(xts(rnorm(1000, 1e-04, 3e-04), Sys.Date() - c((1000):1)))
```
![plot of chunk unnamed-chunk-5](figure/unnamed-chunk-5.png)
EDIT 2
As pointed out by #agstudy it looks like knitr is producing an unnecessary blank image...does anybody know how to remove it?

Resources