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'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 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)
```
I am writing a small exercise book with Markdown. I would like to have the final output with the plots on a column and the document text on the other. Similar problems are addressed here and here. Unfortunately, they mainly desire one output per column. I would like to produce the output on a column and the text on the other. Really interesting is Docco, but it apprently shows the code output with the text.
A possible solution would be the RPres markdown horizontal rule: using ***, it creates two easy to use columns. But I do find documentation on its implementation in Markdown documents.
Here an image showing my results so far and an example of my code:
```{r setoption, cache=TRUE, warning=FALSE, message=FALSE, fig.width=12}
knitr::opts_chunk$set(cache=TRUE, warning=FALSE, message=FALSE, fig.width=4, echo = FALSE)
```
```{r, loadlibraries}
library(knitr)
library(lattice)
```
### Exercise 1 - 22/4/'16
Is the data set shown in the following figure symmetric or skewed? How many modes does this data set have?
```{r 1.1}
e1 <- rep(seq(1, 6, 1), c(6, 4, 2, 2, 4, 6))
barchart(table(e1), horizontal = FALSE, xlab = "", ylab = "Frequency")
```
**Solution:**
The data set is symmetric. Furthermore, it has two modes.
### Exercise 2 - 22/4/'16
Describe the shape of the dataset shown in the following figure.
```{r 2.1}
e2 <- rep(seq(1, 9, 1), c(6, 5, 4, 3, 2, 1, 1, 1, 1))
barchart(table(e2), ylab = "Frequency", horizontal = FALSE)
```
**Solution:**
The dataset is right skewed, also said right skewed, with one mode.
As you're asking for columns, my answer will be: table.
Using pipe_tables, figure and text can be alinged next to each other. However, this comes at a price:
The cells of pipe tables cannot contain block elements like paragraphs and lists, and cannot span multiple lines.
If this limitation is acceptable, pipe_tables provide a quite straightforward solution:
```{r img, fig.show = "hide", echo = FALSE}
library(knitr)
hist(rnorm(1000))
```
Figure|Explanation
-------------------------------|-------------------------
`r include_graphics(paste0(opts_chunk$get("fig.path"), "img-1.png"))`|Histogram of 1000 draws from a standard normal density.
Although the column headers cannot be omitted, you can leave them blank if desired.
Note that I initially suppress the plot (fig.show = "hide") and use include_graphics to include it afterwards. Otherwise, there would be a newline after the plot which disrupts the table.
(In knitr 1.12.3, include_graphics doesn't seem to work properly with inline code chunks. However, the current development version 1.12.25 works well.)
Extension
I hacked together an extension that allows to use a single chunk to generate and show the plots and some more features:
```{r setup, echo = FALSE}
library(knitr)
FigureNextToText <- function(number, # number of plot in chunk
text,
alt = "", # alternative text for image
label = opts_current$get("label"), # set explicitly when using inline!
ext = ".png",
headerL = " ", headerR = " ", # empty string confuses pandoc if only right header is set
widthL = 30, widthR = 30,
...) {
path <- fig_chunk(label = label, ext = ext, number = number, ...)
template <- "%s|%s
%s|%s
![%s](%s)|%s\r\n\r\n"
output <- sprintf(
template,
headerL, headerR,
paste0(rep("-", widthL), collapse = ""), paste0(rep("-", widthR), collapse = ""),
alt, path, text
)
return(asis_output(output))
}
```
```{r img, fig.show = "hide", echo = FALSE, results = "asis"}
library(knitr)
hist(rnorm(1000))
hist(runif(n = 1000, min = 0, max = 10))
FigureNextToText(1, text = "Histogram of draws from standard normal density.", widthL = 50, widthR = 10)
FigureNextToText(2, text = "Histogram of draws from uniform distribution.", headerR = "Explanation", alt = "Histogram 2.")
```
Some text.
`r FigureNextToText(2, text = "The same plot, this time inline.", label = "img", headerR = "Explanation", alt = "Histogram 2.")`
Some more text.
I know that the setup looks a little bit scary, but once FigureNextToText is defined, it can be called quite simply, e.g.:
FigureNextToText(2, text = "Histogram of draws from uniform distribution.", headerR = "Explanation", alt = "Histogram 2.")
Finding the correct values for widthL and widthR is somewhat cumbersome. This is because their effect depends on the number of characters in the cell, i.e. the filename of the image in the MD file and the alt text, too.
I try to create multiple plotly figures in a Rmarkdown document using loop or lapply.
The R script:
require(plotly)
data(iris)
b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")),
function(x) {
plot_ly(iris,
x = iris[["Sepal.Length"]],
y = iris[[x]],
mode = "markers")
})
print(b)
works well, but it fails when included in a knitr chunk:
---
output: html_document
---
```{r,results='asis'}
require(plotly)
data(iris)
b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")),
function(x) {
plot_ly(iris,
x = iris[["Sepal.Length"]],
y = iris[[x]],
mode = "markers")
})
print(b)
```
I tried replacing print(b) with a combination of lapply eval and parse but only the last figure was displayed.
I suspect a scoping/environment issue but I cannot find any solution.
Instead of print(b), put b in htmltools::tagList(), e.g.
```{r}
library(plotly)
b <- lapply(
setdiff(names(iris),
c("Sepal.Length","Species")),
function(x) {
plot_ly(iris,
x = iris[["Sepal.Length"]],
y = iris[[x]],
mode = "markers")
}
)
htmltools::tagList(b)
```
Note: Before Plotly v4 it was necessary to convert the Plotly objects to htmlwidgets using Plotly's as.widget() function. As of Plotly v4 they are htmlwiget objects by default.
For people who are interested in the technical background, you may see this blog post of mine. In short, only top-level expressions get printed.
I found a "dirty" solution by using temp file and kniting it :
```{r,echo=FALSE}
mytempfile<-tempfile()
write("```{r graphlist,echo=FALSE}\n",file=mytempfile)
write(paste("p[[",1:length(p),"]]"),file=mytempfile,append = TRUE)
write("\n```",file=mytempfile,append = TRUE)
```
`r knit_child(mytempfile, quiet=T)`
But it's unsatisfactory.
For anyone struggling with a loop, here's what worked for me.
p=list()
for (n in 1:3){
p[[n]] <- plot_ly(x = 1:100, y = rnorm(100)+n, mode = 'lines', type="scatter")
}
htmltools::tagList(p)
I.e. it doesn't matter if the list p is created in a loop or lapply, etc. as long as you call htmltools::tagList outside the loop.
Thanks to Yihui for helping me get there and for immense work developing and helping with these tools.