R, generate pretty plot by dfSummary - r

I have a problem using summarytools packet. There is tutorial:https://cran.r-project.org/web/packages/summarytools/vignettes/Introduction.html with pretty plots of data:
My problem is that my code generate only TEXT GRAPH. This is chunk of code in my markdown to generate plot:
```{r summary, results='markup'}
library(summarytools)
my_data <- ...
dfSummary(my_data)
```
Unfortunately it generates something like this:
How can I generate this pretty report using summarytools?
Or have you better tools for this? (generate graph, mean, std, etc.)
I found the correct syntax to generate plot:
print(dfSummary(baseline_train), method = 'render')
And the results look like this:

A little update on this:
Always use knitr chunk option results='asis', as someone pointed in an earlier comment.
It is possible to generate summaries including png graphs using print():
print(dfSummary(iris), method = "render")
Starting with version 0.9.0 (available only on GitHub as of Feb. 2019), markdown summaries will also include png graphs provided you specify the following arguments:
plain.ascii = FALSE
style = "grid"
a physical location for temporary png's (tmp.img.dir)
dfSummary(iris, plain.ascii = FALSE, style = "grid", tmp.img.dir = "/tmp")
Additionnal tips
In both cases, you will (in all likelihood) need to adjust the size of the graphs with dfSummary()'s graph.magnif parameter (try values between .75 and .85).
Exclude a column or two to avoid overly wide summaries:
dfSummary(iris, [...], varnumbers = FALSE, valid.col = FALSE)

You need to use results = 'asis' for the code chunk. Here is minimal reproducible example:
---
title: "Untitled"
output: html_document
---
```{r, results='asis'}
library(summarytools)
dfSummary(iris, plain.ascii = FALSE, style = "grid")
```
produces

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.

Remove progress bar from knitr output

I'm analyzing some data and would like to do a Simpsons paradox on R. I've installed the Simpsons package and loaded the library. Here is an example based on the package documentation:
---
output: html_document
---
```{r}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
This is returning a plot with 3 clusters (exactly what I need). However, when I Knit the Rmd file to HTML, I'm getting a lot of equals signs (======) with a percentage next to it like a loading grid which I would like to remove from my final output.
You can suppress any output messages in R by setting the knitr chunk option. If we wish to hide all code output other than plots, we can use the following solution:
---
output: html_document
---
```{r echo=FALSE, results='hide', fig.keep='all', message = FALSE}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
I would note that this package seems to print out a lot more content that most packages, and therefore the combination of options are quite long.
An easier method would probably be to move the plot to a separate chunk and have all the analysis run before it. The include argument can be used to suppress all outputs, but this includes plots, hence why we must use two chunks:
```{r, include = FALSE}
# your code to build model
```
```{r}
plot(example)
```
Check out the full list of knitr chunk options here

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")

Embeded Plots Missing when Knitting to PDF

I know this question has been asked in different formats, but when searching I couldn't find a solution or problem similar to mine.
Using Mac with RStudio (Version 1.0.153 ) R (version 3.4.3 (2017-11-30) -- "Kite-Eating Tree")
I am just trying to knit to a PDF (weave using knitr) in R markdown, but when I do, the plots are missing. When I knit to HTML the plots are there. I am using the earlywarnings package which helps create the plots. See example below using R markdown:
```{r, earlywarnings, fig.keep='all'}
library(earlywarnings)
data("foldbif")
x = foldbif
plot.ts(x)
```
That plot shows in the pdf output, but not when I create other plots like these:
```{r, echo=FALSE,results='hide',fig.keep='all', fig=TRUE}
out<-generic_ews(x,winsize=50,detrending="gaussian",
bandwidth=5,logtransform=FALSE,interpolate=FALSE)
```
or this one:
```{r, echo=FALSE, results='hide', fig.keep='all', fig=TRUE, warning=FALSE}
qda = qda_ews(x, param = NULL, winsize = 50, detrending = "gaussian",
bandwidth = NULL, boots = 100,s_level = 0.05, cutoff = 0.05,
detection.threshold = 0.002, grid.size = 50, logtransform = FALSE, interpolate = FALSE)
```
The last function also only displays 2 out of 3 plots, but I'll figure that out another time.
Any help would be appreciated. Please let me know if this was not clear.
I can confirm that the issue is related with the use of dev.new(). I copy-pasted the code of the function, removed it (the one line 136 of the function) and it worked, i.e. I get the figure on my pdf. There may be a way to call a function to avoid the effect of dev.new() that I am not aware of.

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