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?
Related
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.
I am writing an R Markdown document using the Python engine of {reticulate}. I am quite happy with how it works.
The only thing is, I cannot use r as a Python object name that I'm going to use in multiple chunks.
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
r = 10
print(r) ##> 10
```
```{python}
print(r) ##> <__main__.R object at 0x119ad37d0>
```
I understand r is a good name when we use R objects from within a Python chunk. Since I know I am not going to do that in my project, I would like to use r as a name for my Python object.
Is there any way to change the name, r, for the R object created by reticulate? Or, to tell reticulate not to create r object?
I am aware of the two straightforward workarounds
Don't use r for Python objects.
Write everything in one big chunk and not share r between Python chunks.
but I'd like to have more freedom.
The object name r is special since it is used to communicate between R and python. The same holds for py in R:
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
foo = 10
print(foo) ##> 10
```
```{r}
library(reticulate)
py$foo ##> [1] 10
```
```{r}
foo <- 10
```
```{python}
print(foo) ##> 10
print(r.foo) ##> 10.0
```
Avoiding the use of r as an opject name is therefore the only good possibility I can see.
Still working on the details but I think setting source and output knit hooks may help. My dirty first try looks like this:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::knit_hooks$set(
source = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', "source", tolower(options$engine), x)
},
output = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
paste0('<pre><code>', x, '</code></pre>\n')
}
)
```
```{python, rsub='rrr'}
rrr = 10
print(rrr)
```
```{python, rsub='rrr'}
print(rrr)
```
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.
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.
I have been unable to get external code chunks to work in knitr from a LaTeX (*.Rtex) document.
foo.R contains:
## #knitr foo
#
tx <- seq(0,2*pi,length.out=100)
ty <- cos(tx*3.0)
plot(tx,ty,pch=20,col='blue')
seq(3)
The test1.Rtex document contains:
%% read_chunk('Code/foo.R')
%
%%
%% begin.rcode foo, echo=TRUE, tidy=TRUE, eval=TRUE
%% end.rcode
knit('test1.Rtex') yields:
chunk "foo" is empty or set not to be evaluated
I have a copy of the knitr git repository. Modifying this code with cat(sprint()) statements there is no evidence of read_chunk() being used in LaTeX code.