R markdown table - r

I am working on a paper in R Markdown. I'd like to create a table which contain math symbols. Below, it my simple code with a table:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r echo=FALSE}
library(knitr); library(kableExtra)
df <- data.frame(A=c("Hello!", 100, "$x^2+100$"), L=c(10, "World!", "100+250*1"))
knitr::kable(df, escape = FALSE, booktabs = TRUE,
caption = "An example[note]",
col.names = c("Left", "Right")) %>%
add_indent(c(2, 3), level_of_indent = 1.5, all_cols = TRUE) %>%
add_footnote(c("Source: Book."), notation = "symbol")
```
As a result, every time I knit the file the same error appears:
! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate
I will appreciate if very much if you help me to fix this error.

when I run your example it knits perfectly fine. this is what it looked like in HTML. I haven't seen that error before so I am not sure what the problem is. Perhaps it is a problem with your YAML header, or a line of code previous to the table that is causing problems. Hopefully someone else knows!

Related

Dynamic plots and tables inside Rmarkdown

I am new to Rmarkdown and shiny and forgive me for some naive questions. I have build a code in two parts first where I do all the processing and second where I call the Rmarkdown to knit it.
The first code example.R is as follows and works fine independently (with only glitch of plots being trimmed from sides):
# Create a label for the knitr code chunk name
## #knitr ExternalCodeChunk020
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
The second part of the code (mrkdwn.Rmd) is where I try to knit and generate Rmarkdown report:
---
title: "Code Chunks"
author: "Author"
date: "November 13, 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::read_chunk("example.R")
```
This first code chunk prints the externally located code,
but it does not execute the code. The next code chunk
executes the externally located code, but it does not print code
itself. Text output is suppressed, and figures are plotted,
but only after all of the code is executed.
```{r DisplayCodeChunk, eval = FALSE, echo = FALSE}
<<ExternalCodeChunk020>>
```
```{r RunCodeChunk, echo = FALSE, eval = TRUE, results = 'hide'}
<<ExternalCodeChunk020>>
```
the output doesn't contain plots. I am not sure what is going wrong, could anyone of you help me in fixing this.
I know that an easy fix is to put both parts of the code together inside the Rmarkdown like this:
---
title: "test3"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
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}
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Since I need to process large datasets and generate graphs/plots and table I would prefer to keep them separately, so that my Rmarkdown doesn't crash. May be this is wrong and there could be a better approach, please suggest.
Many thanks for your time and help.

P-values significance not showed in stargazer html regression table

I am having trouble with the Notes significance (asterisks) not appearing when using stargazer to format html tables. The result is ok when using latex.
Here is my source file "teste.Rmd"
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r data}
#some data
set.seed(123)
X = rnorm(500,10,3)
Y = 10+ 3*I(X^1.2) + rnorm(500)
# models
m1 = lm(Y~X)
m2 = lm(Y~X+I(X^2))
```
```{r res,warning=FALSE,message=FALSE,results='asis'}
library(stargazer)
stargazer(m1,m2,type = 'html',title = 'Models' )
```
The result is below
The same with latex produces this
As you can see the asterisks in Notes are formatted correctly with latex but not with html option. How to get the same behavior with html?
Maybe it is a bug as #jaySf said in the comments to the original question. But based on #tmfmnk's answer and htmltools package I ended with a workaround. This is the updated relevant part of the source file.
```{r res,warning=FALSE,message=FALSE,results='hide'}
library(stargazer)
stargazer(m1,m2,type = 'html',title = 'Models', out = "table1.html")
```
```{r, echo=FALSE}
htmltools::includeHTML("table1.html")
```
Now I got the desired result
Try adding customized notes using notes and notes.append parameters as follows:
stargazer(m1,m2,type='html',notes="<span>***</span>: p<0.01; <span>**</span>: p<0.05; <span>*</span>: p<0.1",notes.append=F)
I originally thought that using backslash to escape * will work, e.g. notes="\\*\\*\\*: p<0.01; \\*\\*: p<0.05; \\*: p<0.1". Unfortunately, it doesn't. I also tried to use the HTML code of *, i.e. *, e.g. notes="***: p<0.01; **: p<0.05; *: p<0.1". Still it doesn't work.
However, surrounding * with an HTML tag works. It doesn't have to be <span></span>. I tried <b></b>, etc. and they worked.
When exported through out it is working fine:
stargazer(m1,m2,type = 'html',
title = 'Models',
out = "/path/table.html")

Image footnotes in Bookdown

How can I add a figure note right below the image in bookdown::pdf_document2? It is relatively easy to do for plots that created by ggplot2. grid.arrange can do the work with grid.arrange(<plot>, bottom = <figure_notes>). But if I insert an image manually, e.g., knitr::include_graphics(rep("images/knit-logo.png", 3)), is there a way to add a figure note to it? I saw a knitr option, fig.subcap. But this fails to compile:
```{r fig.show="hold", fig.cap = "a", fig.subcap = "b"}
knitr::include_graphics(rep("images/knit-logo.png", 3))
```
This returns:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (MiKTeX 2.9.6350 64-bit)
entering extended mode
! Undefined control sequence.
<recently read> \subfloat
Error: Failed to compile miniSample.tex. See miniSample.log for more info.
Thanks
If you want to use subfigures, you have to load the subfig package within LaTeX. This can be done by using the header-includes argument in the YAML, as explained here.
Here is a minimal, reproducible example, It creates a local image "temp.jpg" and then produces three subfigures:
---
output: pdf_document
header-includes:
- \usepackage{subfig}
---
```{r}
jpeg(filename = "temp.jpg")
plot(cars)
dev.off()
```
```{r fig.show="hold", fig.cap = "a", fig.subcap = c("Your Caption", "Another Caption", "Isn't this great"), fig.ncol = 3, out.width="33%"}
knitr::include_graphics(rep("temp.jpg", 3))
```
Check out this post for the original description: Subfigures or Subcaptions with knitr?
Found an expedient solution:
Read the image into R using magick::image_read;
Convert the image to raster project with rasterGrob;
Create a note with textGrob; Use grid.arrange to present;
Present the image together with note using grid.arrange.
plot_A <- magick::image_read(<path>) %>% rasterGrob(interpolate = TRUE)
note <- textGrob("This is a note.")
grid.arrange(plot_A, bottom = note)

How to show significance stars in R Markdown (rmarkdown) html output notes?

I want to show regression outputs in HTML documents using R Markdown. I tried the texreg and stargazerpackages. My problem is now, that in the notes I can't bring the significance stars to life. Due to automatic generation it seems I can't escape them. I've been puzzling around with this and this but with no success. What am I missing? Thanks a lot!!
Here's some code:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r data}
library(car)
lm1 <- lm(prestige ~ income + education, data=Duncan)
```
## with STARGAZER
```{r table1, results = "asis", message=FALSE}
library(stargazer)
stargazer(lm1, type="html", notes="stargazer html 1") # nothing
stargazer(lm1, type="html", notes="stargazer html 2", star.char = "\\*") # nothing, even gone in table
```
## with TEXREG
```{r table2, results = "asis", message=FALSE}
library(texreg)
htmlreg(lm1, custom.note="%stars. htmlreg") # nothing
htmlreg(lm1, custom.note="%stars. htmlreg", star.symbol = "\\*") # still nothing!
```
Note: Question was a former sub-question I have now splitted.
Use the HTML entity for the asterisk:
star.symbol='*'
See http://www.ascii.cl/htmlcodes.htm.
You could also add the "legend" manually:
stargazer(lm1, type="html", notes = "<em>*p<0.1;**p<0.05;***p<0.01</em>", notes.append = F)

2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!
NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

Resources