Stargazer tables directly into pdf tables not showing up - r

I have the following R Markdown document. I am trying to render regression output tables directly into pdf, but the tables don't show up. I have tried type = 'latex' instead of type = 'html', but no difference.
I know that I can copy-paste the latex code from the console, but that is really cumbersome. Any other solution to this?
```
---
title: "title"
output:
pdf_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(stargazer)
library(plm)
```
```{r data, echo=FALSE, include=FALSE}
library(haven)
dat <- read_dta("E:/CZ/CZ_fin_distress/CZ_all_2015_2018_small_final.dta")
library(dplyr)
dat <- dat %>%
rename(
log_avgprice = lamt,
log_localprice = lsamt,
negNPM = cat2,
lagged_negNPM = lcat
)
dat <- dat[dat$ptype<3,]
```
```{r prices, echo=FALSE, include=FALSE, results="asis"}
ma <- plm(log_avgprice ~ negNPM, index=c("id", "year"), model="within", data=dat)
mb <- plm(log_localprice ~ negNPM, index=c("id", "year"), model="within" , data=dat)
mc <- plm(log_avgprice ~ lagged_negNPM, index=c("id", "year"), model="within", data=dat)
md <- plm(log_localprice ~ lagged_negNPM, index=c("id", "year"), model="within", data=dat)
stargazer(ma, mb, mc, md, title = "Logged claim amount", type = 'html')
```

I found my mistake: include=FALSE and results="asis" cancel each other out. It works now after eliminating include=FALSE.

Related

Markdown - call a result from a table or a list in the text

Here is an example of what I'm trying to do. I would like to call in the text a result from a table itself coming from a random computation.
---
title: "RĂ©gression logistique"
subtitle: "Analyse quantitative II"
author:
- name: ""
- affiliation:
date: "TP 4"
output:
html_document:
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r message=FALSE}
bystander <- data.frame(reaction = c(rep(0, 30), rep(1, 30)),
age.victime = c(rep(5, 5),rep(85, 5),rep(7, 5),rep(35, 5),rep(45, 5),rep(50, 5)),
sexe.victime = c(rep(0, 20), rep(1, 10), rep(0, 10), rep(1, 20)),
nbrpers = c(11:40, 0:29),
statutse = c(rep(4, 30), rep(18, 30)))
#install.packages("caret")
library(caret)
# install.packages("lmtest")
library(lmtest)
#install.packages("pscl")
library(pscl)
#install.packages("e1071")
library(e1071)
```
```{r}
Train <- createDataPartition(bystander$reaction, p=0.8, list=FALSE)
training <- bystander[ Train, ]
testing <- bystander[ -Train, ]
training$reaction <- as.factor (training$reaction)
model_fit <- train(reaction ~ age.victime + sexe.victime + nbrepers + statutse, data=training, method="glm")
testing$reaction <- as.factor (testing$reaction)
pred <- predict(model_fit, newdata=testing)
confusionMatrix(data=pred, testing$reaction)
```
We obtain a an accuracy of `r confusionMatrix(data=pred, testing$reaction)`.
I just want the Accuracy from the overall in the confusionMatrix. Is there a way to call only this result because my trial is not working there (pretty logical, it's a list), like in latex when you can reference your results and call it later.
Thank's in advance!
To achieve your desired result assign the result of calling caret::confusionMatrix to variable. Afterwards you could access the Accuracy in an inline chunk like so:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(caret)
```
```{r}
conf_mat <- caret::confusionMatrix(iris$Species, sample(iris$Species))
```
We obtain an accuracy of `r conf_mat$overall[["Accuracy"]]`.

Table rendering in pdf document using R markdown

After days trying to find a solution, I give up and ask for help.
I decided to use R Markdown very recently. While I can render plots as I want, I cannot succeed in rendering my tables in a pdf doc properly.
Here the corresponding [EDITED]code:
---
title: "My_title"
output:
pdf_document: default
html_document:
df_print: paged
params:
date: "!r Sys.Date()"
---
```{r library, echo=F, message=F, warning=F, paged.print=FALSE}
suppressMessages(library("knitr"))
suppressMessages(library(reshape2))
suppressMessages(library(splines))
suppressMessages(library(kableExtra))
suppressMessages(library(gplots))
```
```{r, setup, echo = F}
opts_knit$set(root.dir = "my_path")
knitr::opts_chunk$set(echo = F)
```
```{r}
dt <- expand.grid(Region=c("a","b","c"), Country=c("d","e","f"), Cancer= c("All", "CRC", "Breast"),
age.1.1=1:2,
age.1.2=1:2,
age.1.3=1:2)
```
```{r Table_1, INCLUDE = TRUE}
cancer.lab <- c("All", "CRC", "Breast")
for (i in 1:3){
b <- dt[dt$Cancer==cancer.lab[i],]
b <- b[,-3]
t <- kable(b, format = ,caption = "Fig", row.names = F) %>%
kable_paper() %>%
kable_styling(font_size = 9) %>%
add_header_above(c(" " = 2, "1998" = 3))
print(t)
}
```
Again I am new and I surely miss something.
I use Mac if it may explain something.
Thank you for your help.
Sophie.
I think this is the same issue as dealt with here: https://stackoverflow.com/a/53632154/2554330. The problem is that you need to use knit_print to print the tables, but you can't do that in a loop.
So if you change the last code chunk to this, it should work:
```{r Table_1, INCLUDE = TRUE}
results <- c()
cancer.lab <- c("All", "CRC", "Breast")
for (i in 1:3){
b <- dt[dt$Cancer==cancer.lab[i],]
b <- b[,-3]
t <- kable(b, format = ,caption = "Fig", row.names = F) %>%
kable_paper() %>%
kable_styling(font_size = 9) %>%
add_header_above(c(" " = 2, "1998" = 3))
results <- c(results, knit_print(t))
}
asis_output(results)
```

dynamic tabsets with multiple plots r markdown

I managed to create a html document that creates dynamic tabsets based on a list of items. Adding one plot works fine on one tabset. How can I add now multiple plots on one tabset?
Hereby the code I started from but it only shows 1 plot per tabset when you knit the document to html output. obviously there is still something missing.
---
title: "R Notebook"
output:
html_document:
df_print: paged
editor_options:
chunk_output_type: inline
---
### header 1
```{r}
library(ggplot2)
df <- mtcars
pl_list <- list()
pl1 <- qplot(cyl, disp, data = df[1:12,])
pl2 <- qplot(mpg, cyl, data = df[13:20,])
pl3 <- qplot(mpg, cyl, data = df[21:30,])
pl4 <- qplot(mpg, cyl, data = df[1:12,])
pl_list[[1]] <- list(pl1, pl3, "one")
pl_list[[2]] <- list(pl2, pl4, "two")
```
### header {.tabset}
```{r, results = 'asis', echo = FALSE}
for (i in seq_along(pl_list)){
tmp <- pl_list[[i]]
cat("####", tmp[[3]], " \n")
print(tmp[1])
cat(" \n\n")
}
```
There are a couple of improvements you can do.
Create cat header function with arguments for text and level.
With it you don't need to call cat multiple times and it creates wanted number of # automatically.
catHeader <- function(text = "", level = 3) {
cat(paste0("\n\n",
paste(rep("#", level), collapse = ""),
" ", text, "\n"))
}
print plots using lapply.
Full code looks like this:
---
title: "R Notebook"
output:
html_document:
df_print: paged
editor_options:
chunk_output_type: inline
---
```{r, functions}
catHeader <- function(text = "", level = 3) {
cat(paste0("\n\n",
paste(rep("#", level), collapse = ""),
" ", text, "\n"))
}
```
### header 1
```{r}
library(ggplot2)
df <- mtcars
pl_list <- list()
pl1 <- qplot(cyl, disp, data = df[1:12,])
pl2 <- qplot(mpg, cyl, data = df[13:20,])
pl3 <- qplot(mpg, cyl, data = df[21:30,])
pl4 <- qplot(mpg, cyl, data = df[1:12,])
pl_list[[1]] <- list(pl1, pl3, "one")
pl_list[[2]] <- list(pl2, pl4, "two")
```
## header {.tabset}
```{r, results = "asis", echo = FALSE}
for(i in seq_along(pl_list)){
tmp <- pl_list[[i]]
# As you want to use tabset level here has to be lower than
# parent level (ie, parent is 2, so here you have to use 3)
catHeader(tmp[[3]], 3)
lapply(tmp[1:2], print)
}
```

Group only some columns in LaTeX table using R

I am trying to create a table in RMarkdown that looks similar to the following example:
---
title: "Example"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r cars, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(Hmisc)
latex(mtcars, file = "", cgroup = c("mpg", "cyl"), n.cgroup = c(1,10))
```
I would like to group columns 2 through 10. Any ideas on how I can accomplish this with the Hmisc package or any other R package?
I think just using a blank header name for the first column gives you what you want:
latex(mtcars, file = "", cgroup = c("", "cyl"), n.cgroup = c(1,10))
Result:
Using my package:
library(huxtable)
hux_cars <- as_hux(mtcars, add_colnames = TRUE)
hux_cars <- insert_row(hux_cars, c('mtcars', 'cyl', rep('', 9)))
colspan(hux_cars)[1, 2] <- 10
align(hux_cars)[1, 2] <- 'centre'
bold(hux_cars)[1, ] <- TRUE
position(hux_cars) <- 'left'
quick_pdf(hux_cars)
Which produces:

Why does datatable not print when looping in rmarkdown?

I am working on creating a dynamic rmarkdown document. The end result should create a tab for each 'classification' in the data. Each tab should have a datatable, from the DT package, with the data printed to it. Below is the code I have been using:
---
output: html_document
---
# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```
```{r data.setup}
set.seed = 1242
rows = 64
data.1 = runif(rows, 25, 75)
data.2 = runif(rows, .01, 1)
data.3 = runif(rows, 1, 10)
classification = c("A", "B", "C", "D")
df = data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 = as.numeric(df$data.1)
df$data.2 = as.numeric(df$data.2)
df$data.3 = as.numeric(df$data.3)
```
```{r results= 'asis'}
for(j in levels(df$classification)){
df.j = df[df$classification == j, ]
cat(paste("\n\n## Classification: ", j, "##\n"))
w = datatable(df.j)
#datatable(df.j)
print(w)
}
```
Notice I have commented out straight calls to the datatable function, those were not printing to rmarkdown. The results of the call as written generate an html document with the correct tabs, but no datatables in them. Additionally, the datatables actually display in my RStudio session with the correct subsetting. As a test, I tried achieving the goal using the kable function from knitr, and the tables were printed in their appropriate tabs, unfortunately, kable does not have all the functionality required.
This is not a complete answer as some of this is still puzzling me, but at least this is good enough to get you going while I try to understand some more.
---
output: html_document
---
# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```
```{r data.setup}
set.seed <- 1242
rows <- 64
data.1 <- runif(rows, 25, 75)
data.2 <- runif(rows, .01, 1)
data.3 <- runif(rows, 1, 10)
classification <- c("A", "B", "C", "D")
df <- data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 <- as.numeric(df$data.1)
df$data.2 <- as.numeric(df$data.2)
df$data.3 <- as.numeric(df$data.3)
```
```{r include = FALSE}
# Why, oh why do I need this chunk?
datatable(df)
```
```{r results = 'asis'}
for(j in unique(df$classification)){ # You were using level() here, so your for-loop never got off the ground
df.j <- df[df$classification == j, ]
cat(paste("\n\n## Classification: ", j, "##\n"))
print( htmltools::tagList(datatable(df.j)) )
}
The third chunk is required for this to work, I'm not yet sure why.
Reaching here by googling the same question. This has worked for me: https://gist.github.com/ReportMort/9ccb544a337fd1778179.
Basically, generate a list of rendered tibbles and manually call knit.
Here is a working Rmd based on your example, using the technique found in the above link:
---
output: html_document
---
# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```
```{r data.setup}
set.seed <- 1242
rows <- 64
data.1 <- runif(rows, 25, 75)
data.2 <- runif(rows, .01, 1)
data.3 <- runif(rows, 1, 10)
classification <- c("A", "B", "C", "D")
df <- data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 <- as.numeric(df$data.1)
df$data.2 <- as.numeric(df$data.2)
df$data.3 <- as.numeric(df$data.3)
```
```{r include = FALSE}
# prepare a list of 4 sub-dataframes, each corresponding to one classification
df_list <- split(df, df$classification)
```
```{r create-markdown-chunks-dynamically, include=FALSE}
out = NULL
for (c in names(df_list)) {
knit_expanded <- paste0("\n\n## Classification: ", c, "##\n\n```{r results='asis', echo=FALSE}\n\ndatatable(df_list[['", c, "']])\n\n```")
out = c(out, knit_expanded)
}
```
<!--- knit those table chunk statements -->
`r paste(knit(text = out), collapse = '\n')`

Resources