Been learning how to use Drake today and managed to migrate my code but not my R markdown reports yet. This report compiles fine, and produces the expected output, but also gives this error which no amount of searching has shed light on.
I am using the r_make() command as recommended, and my plan so far reads:
plan_0 <- drake_plan(
raw_c_data = read_rds(
file_in("data/css_carib_data.rds")),
raw_c_fg = read_rds(
file_in("data/css_carib_fg.rds")),
c_data = clean_caribbean_fg(raw_c_data, raw_c_fg),
clean_c_fg = write_rds(
c_data,
file_out("data/clean_c_fg.rds"),
compress = "gz"),
c_maps = gen_maps(bbx_1, bbx_2, bbx_3, bbx_4, bbx_5),
c_maps_out = write_rds(
c_maps,
file_out("data/c_maps.rds"),
compress = "gz"),
c_base_report = rmarkdown::render(
knitr_in("R/0_prepare_data.Rmd"),
output_file = file_out("0_prepare_data.html"),
quiet = T)
)
That Rmd file starts with the following
---
title: "0: Data Description"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
require(drake)
require(tidyverse)
require(ggmap)
loadd(raw_c_fg)
loadd(clean_c_fg)
loadd(c_maps)
```
This document is a description of the data processed in `0_prepare_data.R` from the Caribbean region. The following table gives the counts of each classification within the aggregated functional groups.
```{r tables, echo = F}
raw_c_fg %>%
pull(fg) %>%
table() %>%
knitr::kable(col.names = c("Class", "Count"),
caption = "Counts of Each Functional Group")
```
I'm happy to attach as much more as required, but hopefully this is enough to see why I am getting this error?
Figured out what was going wrong, and it was the usual conflict between Rmd and Rproj/drake with relative locations. I had located the Rmd file within the R directory, but _drake.R was in the base directory, and so the differences in locating the output were causing drake to look in the wrong place.
Related
Below is the code that is presenting the problem.
I can't seem to find a way to have it not print the source data before the table, house. Is this a code chunk option issue such as not having include = False in the code? To produce, you would create a new R markdown document and then put the code below in the first two code chunks (usually gray background color).
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
pkgs <- c("tidyverse","tidyquant","RODBC", "RODBCDBI",
"spdplyr","rgdal","readxl","Rcpp",
"RcppRoll", "ggforce","scales", "DBI","ggthemes",
"cowplot","gt","data.table","gridExtra","ggrepel","htmltab","tigris","tidycensus")
loader <- function(x){
for( i in x ){
if(!require(i, character.only = TRUE) ){
install.packages(i, dependencies = TRUE)
require(i, character.only = TRUE)
}
}
}
loader(pkgs)
#lapply(pkgs,library,character.only = TRUE)
```
## Housing Price
```{r, echo=FALSE,comment=FALSE,message=FALSE}
# load data
dt <- fread("http://www.freddiemac.com/fmac-resources/research/docs/fmhpi_master_file.csv")
dt[,hpa_yoy:=Index_SA/shift(Index_SA,12)-1,.(GEO_Type,GEO_Code,GEO_Name)]
dt_nv<- dt[GEO_Name=="NV" & Year>2010,]
head(dt_nv)
dcast(dt_nv,Year~Month,value.var="hpa_yoy")
dt_nv[,mname:=factor(month.abb[Month],levels=month.abb)]
dt_tab <- dcast(dt_nv,Year~mname,value.var="hpa_yoy")
house<- gt(dt_tab) %>%
opt_row_striping()%>%
fmt_percent(
columns = c(month.abb),
decimals = 1,
use_seps = FALSE
) %>%
tab_header(title="Nevada House Price Growth",
subtitle="12-month % change in Freddie Mac House Price Index" )%>%
tab_options(
data_row.padding = px(9),
row_group.padding = px(9),
table.font.size = px(11),
source_notes.font.size = px(11),
source_notes.padding = px(1))
```
## Including Plots
Housing Prices
```{r, echo=FALSE, message=FALSE}
house
```
Really unclear what the question is and I am not installing all of these packages, but from what I can tell, you need to put include=FALSE into the header of the second chunk.
The lines:
dt[,hpa_yoy:=Index_SA/shift(Index_SA,12)-1,.(GEO_Type,GEO_Code,GEO_Name)]
and head(dt_nv)
that are causing problems because they are not assigned to any object, R is just printing the table described by these line, I think.
If you are desperate, make this code eval=FALSE and then copy the code into another chunk with include=FALSE so the first block is there for show, while the actual block is evaluated without being shown in the document.
I'm trying to print an R help file vignette in an R notebook chunk for output into an HTML file. I want the entire vignette to show up as output in the HTML notebook preview because it serves as a nice data dictionary for a quick regression example. Using library(mlbench), I tried:
print(?BostonHousing2)
and I tried just calling
?BostonHousing2
in the code chunks, and neither of them output to the HTML file, they just populate in the Help tab inside of RStudio.
Anyone have any ideas?
Here is a way (if I correctly understand what you want). But maybe not the best one.
---
title: "Untitled"
author: "Stéphane Laurent"
date: "29 février 2020"
output: html_document
---
```{r setup, include=FALSE}
library(gbRd) # for Rd_fun
```
```{r, results='asis'}
Rd <- Rd_fun(help("pretty"))
htmlfile <- tempfile(fileext = ".html")
tools::Rd2HTML(Rd, htmlfile, package = "",
stages = c("install", "render"))
htmllines <- readLines(htmlfile)
i <- grep("<body>", htmllines)
j <- grep("</body>", htmllines)
cat(htmllines[(i+1):(j-1)], sep = "\n")
```
Based on Noam Ross's solution, and modified with some of the code in Stéphane Laurent's answer, the following function can be used to return an HTML version of the help file
help_console <- function(topic, package,
format=c("text", "html", "latex", "Rd"),
before=NULL, after=NULL) {
# topic - the command for which help is required
# package - the package name with the required topic
# format - output format
# before - place code before the output e.g. "<blockquote>"
# after - place code after the output e.g. "</blockquote>"
# based on code by Noam Ross
# http://www.noamross.net/archives/2013-06-18-helpconsoleexample/
# Stéphane Laurent
# https://stackoverflow.com/questions/60468080/
# print-an-r-help-file-vignette-as-output-into-an-r-html-notebook
# and Michael Sumner (mdsumner)
# https://stackoverflow.com/questions/7495685/
# how-to-access-the-help-documentation-rd-source-files-in-r
format <- match.arg(format)
if (!is.character(topic)) topic <- deparse(substitute(topic))
db <- tools::Rd_db(package)
helpfile <- db[paste0(topic, ".Rd")][[1]]
hs <- capture.output(
switch(
format,
text = tools::Rd2txt(helpfile),
html = tools::Rd2HTML(
helpfile,
package = "",
stages = c("install", "render")
),
latex = tools::Rd2latex(helpfile),
Rd = tools:::prepare_Rd(helpfile)
)
)
if (format == "html") {
i <- grep("<body>", hs)
j <- grep("</body>", hs)
hs <- hs[(i+1):(j-1)]
}
hs <- c(before, hs, after)
hs <- cat(hs, sep = "\n")
invisible(hs)
}
Which then can be used as follow in a RMarkdown document, ready for knitting:
```{r, echo = FALSE, results = "asis"}
help_console("pretty", "base", format = "html")
```
As usual, the R chunk needs to be set to results = "asis" to output to HTML.
This solution does not require the gbRd package.
For some strange reason, I can Knit to html_vignette from RStudio's Knit dropdown, but cannot successfully Build Document from the RStudio menu with Project Options - Build Tools - Roxygen Configure - Vignettes enabled, with the error
Error: Sections \title, and \name must exist and be unique in Rd files
thrown when trying to use the help_console function.
However, I was able to successfully able to create the HTML vignette and incorporate into a package with A-breeze's solution, or building a source or binary package (building source/binary packages can be done from RStudio's "build" menu).
I've been trying to generate a sequence of graph plots inside rmarkdown html compiler...
```{r, include=T, echo=F, fig.height=4, fig.width=10,warning=FALSE}
Here direct is the directory where the files are listed from
"files" is the list of files objects in the transaction form needed for the read.transaction function argument
direct <- "......"
files <- list.files(path = ".....")
for (i in 1:length(files)) {
tr<-read.transactions(file = paste(as.character(direct),"/",files[i],sep = ""),format = "basket",sep = ",")
rules <- apriori(tr, parameter = list(supp=sup, conf=confid))
rules <- sort(rules, by='count', decreasing = TRUE)
plotr <- plot(rules, method = "graph", engine = "htmlwidget")
}
```
I have tried print(plotr), printing just plot(rules,...) and nothing seems to work.
The problem is when I knit the markdown, the plot of the different transaction files doesn't pop up in the html generated by the .Rmd file. Consider that this loop is inside a function that runs inside the chunk.
It would be nice if someone could help me try to solve this problem. If its worth for something, I am trying to generate a report that returns different plot rules based on the apriori algorithm applied to the different files.
If anyone has any idea how this could be solved would be a great help, thank you.
To put multiple htmlWidgets in one RMarkdown chunk you need to create a taglist. Here is an example:
---
title: "Example RMarkdown with multiple arulesViz htmlWidgets in one chunk"
output: html_document
---
```{r}
library(arulesViz)
data(Groceries)
rules <- apriori(Groceries, parameter=list(support=0.001, confidence=0.8))
widget_list <- lapply(1:10, FUN = function(i)
plot(sample(rules, size = 10), method = "graph", engine = "htmlwidget"))
htmltools::tagList(widget_list)
```
You can also use a regular loop to populate the list. More information on this issue can be found at https://github.com/rstudio/DT/issues/67
To hide the messages from library and apriori in the resulting document you can do this:
---
title: "Example RMarkdown with multiple arulesViz htmlWidgets in one chunk"
output: html_document
---
<!-- Hide the messages for library -->
```{r, echo = FALSE, results = FALSE, warning = FALSE, message = FALSE}
library(arulesViz)
```
<!-- verbose = FALSE hides the progress report for apriori -->
```{r}
library(arulesViz)
data(Groceries)
rules <- apriori(Groceries, parameter=list(support=0.001, confidence=0.8),
control = list(verbose = FALSE))
widget_list <- lapply(1:10, FUN = function(i)
plot(sample(rules, size = 10), method = "graph", engine = "htmlwidget"))
htmltools::tagList(widget_list)
```
I've run my analyses in a source Rmd file and would like to knit a clean version from a final Rmd file using only a few of the chunks from the source. I've seen a few answers with regard to pulling all of the chunks from a source Rmd in Source code from Rmd file within another Rmd and How to source R Markdown file like `source('myfile.r')`?. I share the concern with these posts in that I don't want to port out a separate .R file, which seems to be the only way that read_chunk works.
I think I'm at the point where I can import the source Rmd, but now I'm not sure how to call specific chunks from it in the final Rmd. Here's a reproducible example:
SourceCode.Rmd
---
title: "Source Code"
output:
pdf_document:
latex_engine: xelatex
---
```{r}
# Load libraries
library(knitr) # Create tables
library(kableExtra) # Table formatting
# Create a dataframe
df <- data.frame(x = 1:10,
y = 11:20,
z = 21:30)
```
Some explanatory text
```{r table1}
# Potentially big block of stuff I don't want to have to copy/paste
# But I want it in the final document
kable(df, booktabs=TRUE,
caption="Big long title for whatever") %>%
kable_styling(latex_options=c("striped","HOLD_position")) %>%
column_spec(1, width="5cm") %>%
column_spec(2, width="2cm") %>%
column_spec(3, width="3cm")
```
[Some other text, plus a bunch of other chunks I don't need for anyone to see in the clean version.]
```{r}
save(df, file="Source.Rdata")
```
FinalDoc.Rmd
---
title: "Final Doc"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
# Load libraries and data
library(knitr) # Create tables
library(kableExtra) # Table formatting
opts_chunk$set(echo = FALSE)
load("Source.Rdata")
```
As far as I can tell, this is likely the best way to load up SourceCode.Rmd (from the first linked source above):
```{r}
options(knitr.duplicate.label = 'allow')
source_rmd2 <- function(file, local = FALSE, ...){
options(knitr.duplicate.label = 'allow')
tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(file, output=tempR, quiet = TRUE)
envir <- globalenv()
source(tempR, local = envir, ...)
}
source_rmd2("SourceCode.Rmd")
```
At this point, I'm at a loss as to how to call the specific chunk table1 from SourceCode.Rmd. I've tried the following as per instructions here with no success:
```{r table1}
```
```{r}
<<table1>>
```
The first seems to do nothing, and the second throws an unexpected input in "<<" error.
I wrote a function source_rmd_chunks() that sources chunk(s) by label name. See gist.
I am trying to render a sparktable using Rmarkdown. But the output always comes out in raw html or tex format. This depends on whether I am rendering a PDF or an HTML. Not sure what to do here?
library(sparkTable)
data("AT_Soccer")
content <- list(
function(x) {sum(x)},
function(x) {round(sum(x),2)},
function(x) {round(sum(x), 2)},
newSparkLine(lineWidth = 2,pointWidth = 6),
newSparkBar()
)
names(content) <- c("Points","ShotGoal","GetGoal","GoalDiff","winLose")
vars <- c("points","shotgoal","getgoal","goaldiff","wl")
stab <- newSparkTable(AT_Soccer,content,vars)
export(stab, outputType = "html") ### For HTML R-Markdown files
export(stab, outputType = "tex") #### For PDF R-Markdown files
My output (for html files) looks like:
The pdf output is:
I am trying to get the actual sparktable. I have been able to render the actual table like this:
showSparkTable(stab)
However, that opens the spark table within the Shiny framework. I'm trying to produce multiple rmarkdown documents with spark tables.
I took this example from: https://journal.r-project.org/archive/2015-1/templ-kowarik-meindl.pdf. Page 29.
Solution for HTML
Setting this worked for me. Thanks to Martin. Still stuck on the pdf one though.
knitr::opts_chunk$set(results = 'asis')
After studying the documentation a bit I summarize what I learned about including sparkTables inside Rmd documents:
1. For HTML documents (outputType = 'html'):
Just as I said use the chunk option results = 'asis'.
2. For PDF documents (outputType = 'tex'):
You also need the option above in the case of PDF documents. BUT if you dont use it, you will see the plain LaTeX that is generated by export().
At the very bottom of that output you will find an important hint:
## Information: please do not forget to add the following command before \begin{document} in your tex-fi
##
## \newcommand{\graph}[3]{ \raisebox{-#1mm}{\includegraphics[height=#2em]{#3}}}
So what we have to do here is to
include that line of LateX in our preamble,
add results = 'asis' to the code chunk,
and set the argument infonote of export() to FALSE.
The last point prevents another error that the LaTeX compiler would throw (namely that we already have defined the command \graph).
What follows is a working example for a PDF document:
---
title: "Plotting Plots Under Code"
author: "Martin"
date: "February 1, 2017"
output: pdf_document
header-includes:
- \newcommand{\graph}[3]{ \raisebox{-#1mm}{\includegraphics[height=#2em]{#3}}}
---
```{r setup, echo = F, warning = F, message = F, results = 'asis'}
library(sparkTable)
data('AT_Soccer')
content <- list(
function(x) {sum(x)},
function(x) {round(sum(x), 2)},
function(x) {round(sum(x), 2)},
newSparkLine(lineWidth = 2, pointWidth = 6),
newSparkBar()
)
names(content) <- c('Points', 'ShotGoal', 'GetGoal', 'GoalDiff', 'winLose')
vars <- c('points', 'shotgoal', 'getgoal', 'goaldiff', 'wl')
stab <- newSparkTable(AT_Soccer, content, vars)
export(stab, outputType = 'tex', infonote = F)
```