kable prints stargazer table with multiple lines - r

I want to print stargazer table using kable.
When I am running the code in markdown, I get the stargazer table but with multiple lines with the sign | between those lines before the table.
I also get a warning message at the beginning:
Warning in kable_markdown(x = structure(c("", "<table style=\"text-
align:center\"><caption><strong>Crude models: OR for mRS at discharge >3
with 95% CI</strong></caption>", : The table should have a header (column
names)
my output looks like this:
This is my code for the table (with some changes):
mod.example1 <- glm(bad_outcome~x1+x2+x3+x4, family = "binomial", data = dat0)
mod.example2 <- glm(bad_outcome~x1+x2+x3+x4, family = "binomial", data = dat1)
CI.list <- list(exp(confint(mod.example1)),exp(confint(mod.example2)))
my.stg <- stargazer(
title = "my models: OR for bad outcome",
mod.example1
mod.example2,
type="html",
digits = 2,
t.auto = FALSE,
model.numbers = F,
keep.stat = "n",
report = c("vc*sp"),
omit = "Constant",
star.cutoffs = c(0.05,0.01,0.001),
no.space = FALSE,
single.row = F,
dep.var.labels = c("***bad outcome***"),
covariate.labels = c("x1","x2","x3","x4"),
column.labels = c("-**dat0**-", "-**dat1**-"),
ci= T,
ci.custom = CI.list,
apply.coef=exp)
and in a new chunk:
kable(my.stg)
The table is printed but only after the multiple lines / rectangles.
I also ran the code from other computers and then the problem did not happen.
What could cause this?

Update : after a lot of research, i recognized that the problem occurred only after updating my R version from 3.4.0 to 3.4.1.
After updating to the new version, it also made me update knitr package from 1.16 to 1.17 and only that version gives the mentioned error.
So, i downgraded knitr from 1.17 to 1.16 and that solved the problem.

You do not need to use kable() function for generating stargrazer tables in markdown. Just add {r results='asis'} to the beginning of the chunk which includes stargrazer().

Related

LyX: kableExtra problem (perhaps a bug) in column_spec

I create a table in LyX 2.3.6 / TeX Live 2020 as per the following minimal example:
<<results = "asis",echo = F, warning = FALSE, tidy=FALSE>>=
library(dplyr)
library(kableExtra)
df <- data.frame(Female = c(1.52, -0.03), Male = c(1.34, -0.02) )
rownames(df) <- c("Apples", "Bananas")
kable(df, format = "latex", booktabs = T, linesep = "", row.names = TRUE,
align = c("l", "r", "r"), escape = FALSE) %>%
kable_styling("striped", full_width = F, font_size = 10 )
#
This prints perfectly (it is centered on the page), but gives me no control over the column width. If I add a single line with a column_spec statement, I get an error that I don't understand. If the chunk is extend to read
<<results = "asis",echo = F, warning = FALSE, tidy=FALSE>>=
library(dplyr)
library(kableExtra)
df <- data.frame(Female = c(1.52, -0.03), Male = c(1.34, -0.02) )
rownames(df) <- c("Apples", "Bananas")
kable(df, format = "latex", booktabs = T, linesep = "", row.names = TRUE,
align = c("l", "r", "r"), escape = FALSE) %>%
kable_styling("striped", full_width = F, font_size = 10 ) %>%
column_spec(1, width = "6 em")
#
The table is now left justified, not centered on the page, all columns are centered instead of left and right justified, the letter "c" is printed above the table, and the error log shows the following message:
! Undefined control sequence.
<argument> >{\raggedright \arraybackslash
}p{6em}lr
l.149 ...}{>{\raggedright\arraybackslash}p{6em}lr}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.
! LaTeX Error: Illegal character in array arg.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.149 ...}{>{\raggedright\arraybackslash}p{6em}lr}
You're in trouble here. Try typing <return> to proceed.
If that doesn't work, type X <return> to quit.
! LaTeX Error: Illegal character in array arg.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.149 ...}{>{\raggedright\arraybackslash}p{6em}lr}
You're in trouble here. Try typing <return> to proceed.
If that doesn't work, type X <return> to quit.
[2] (./Kable_Explorations.aux)
Package rerunfilecheck Info: File `Kable_Explorations.out' has not changed.
(rerunfilecheck) Checksum: D41D8CD98F00B204E9800998ECF8427E;0.
)
I'd be very appreciative for any help and guidance on the root cause of the problem and how it can be fixed.
Sincerely
Thomas Philips
The creator of the package provided the solution: he made some changes to column_spec to add conditional formatting support and to allow the insertion of images into columns (see https://haozhu233.github.io/kableExtra/awesome_table_in_html.html#Insert_Images_into_Columns), and column_spec() requires the latex array package to be loaded in the preamble. Updating my Latex preamble as follows solves the problem completely:
\usepackage{array}
\usepackage{booktabs}
\usepackage{threeparttablex}
In fact, he suggested that a user might want to load all the latex packages mentioned on this page (https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf#page=4) but I found the 3 mentioned above to be more than adequate for my relatively simple purposes.

Kable footnotes with math equation and alphabetic notes

I'm having trouble with kable and R Markdown. I would like to create a table with footnotes:
1. a bit of math formula (),
2. with alphabetical notes,
3. and I would like the notes a and b to also show up next to var_a and var_b in superscript.
I can make the table, but the moment I add the footnotes I get an error msg.
var_a <- rep(0, 3)
var_b <- rep(1,3)
var_c <- rep(2, 3)
df <- data.frame(var_a=var_a, var_b=var_b, var_c=var_c)
kable(df, "latex", caption = "title", booktabs = T) %>%
kable_styling() %>%
add_footnote("Standard errors in parenthesis. P-values in brackets.", "P-values from Wald-test for $H_0$ Hazard Ratio = 1.",
footnote_order = c("alphabet", "alphabet"))
EDIT:
This is the error msg I get:
Error in add_footnote(., "Standard errors in parenthesis. P-values in brackets.", :
unused argument (footnote_order = c("alphabet", "alphabet"))
To begin with, I'm not a big fan of the pipe operator, when you make complex functions you tend to miss some tiny issues, like putting your footnotes in a vector:
mytable <- kable(df, "latex", caption = "title", booktabs = T)
mytable <- kable_styling(mytable)
add_footnote(mytable,c("Standard errors in parenthesis. P-values in brackets.",
"P-values from Wald-test for $H_0$ Hazard Ratio = 1.") )
I delete footnote_order I don't understand why you use it? And I'm not able to make it work...
I you want footnote to generate $H_0$ instead of \$H\_0\$, you have to write:
add_footnote(mytable,c("Standard errors in parenthesis. P-values in brackets.",
"P-values from Wald-test for $H_0$ Hazard Ratio = 1."), escape = FALSE )

Output from mediate function in RMarkdown

Im trying to inculde the output of the mediate function from mediation package in my RMarkdown (PDF) document. Using summary it gives me the table with the results from the bootstrapping analysis when I knitr the RMarkdown to a PDF document, but:
I don't like the look of the output and wuld like to have a more shiny table.
I can't lable this table with a caption and it's not included in the autmatic nummeration of RMarkdown (and as a consequence I can't reference it in the text).
I tried to use kable or xtabs with the output of the 'mediate` function but it won't work since both functions don't accept the class ("summary.mediate" "mediate") of the output.
This is how the code chunk in my RMarkdown document loks like:
```{r med.y1.z6.z7.c, echo = F, comment = "", strip.white = T, fig.cap="test"}
regDFM <- na.omit(as.data.frame(cbind(Y1, X1, Z1, Z6, Z7)))
regFIT1.C.medY <- lm(Y1 ~ X1+Z1+Z6+Z7+X1:Z1, data = regDFM)
regFIT1.C.medM <- lm(Z7 ~ X1+Z1+Z6+X1:Z1, data = regDFM)
fitMED <- mediation::mediate(regFIT1.C.medM, regFIT1.C.medY,
boot = T, sims = 10, treat="Z6", mediator="Z7")
summary(fitMED)
```
Any help or ideas are very appreciated!
With kable and the elements of the mediate function I finally created a nice RMarkdown > PDF output.
First I created a data.frame using the relevant elements of the mediate function (are the called 'elements'? what would yu call them?). Then just passing the data.frame to kable.
Thanks to #henrik_ibsen for the hint.
Here is my code:
regDFM <- na.omit(as.data.frame(cbind(Y1, X1, Z1, Z6, Z7)))
regFIT1.C.medY <- lm(Y1 ~ X1+Z1+Z6+Z7+X1:Z1, data = regDFM)
regFIT1.C.medM <- lm(Z7 ~ X1+Z1+Z6+X1:Z1, data = regDFM)
fitMED <- mediation::mediate(regFIT1.C.medM, regFIT1.C.medY,
boot = T, sims = 10, treat="Z6", mediator="Z7")
bt_effect <- c("Indirekter Effekt", "Direkter Effekt", "Gesamt Effekt",
"Anteil direkter Effekt")
bt_est <- c(fitMED$d1, fitMED$z1, fitMED$tau.coef, fitMED$n1)
#bt_p <- format.pval(c(fitMED$d1.p, fitMED$z1.p, fitMED$tau.p, fitMED$n1.p))
bt_p <- c(fitMED$d1.p, fitMED$z1.p, fitMED$tau.p, fitMED$n1.p)
bt_stars <- c(stars.pval(fitMED$d1.p), stars.pval(fitMED$z1.p),
stars.pval(fitMED$tau.p), stars.pval(fitMED$n1.p))
bt_DF <- data.frame(row.names = bt_effect, format(bt_est, digits = 2),
format(bt_p, nsmall = 3), bt_stars)
colnames(bt_DF) <- c("Koeffizienten", "p-Werte", "")
kable(bt_DF, booktabs = T, align = "c",
caption = "Bootstraping-Analyse für Mediation") %>%
footnote(general = c("Simulationen: 1000", "Signifikanzniveaus: ∗ p<0.05;
∗∗ p<0.01; ∗∗∗ p<0.001"),
general_title = "Anmerkungen:")

automatically add version changing table note in R Sweave

need your help for a little problem, I'm using R Sweave to generate dynamic report, and the code is :
industryTable<-data.frame("Industry" = INDUSTRY.DATA[1:15,]$industryname,
"Freq" = INDUSTRY.DATA[1:15,]$Freq,
"Perc" = INDUSTRY.DATA[1:15,]$Perc,
"Industry" = INDUSTRY.DATA[16:30,]$industryname,
"Freq" = INDUSTRY.DATA[16:30,]$Freq,
"Perc" = INDUSTRY.DATA[16:30,]$Perc)
names(industryTable)<-c("Industry", "Freq","Perc","Industry", "Freq","Perc")
add.to.row <- list(pos = list(nrow(industryTable)), command = NULL)
comm <- paste0("\\hline \n \\multicolumn{",dim(industryTable)[2],"}{l}",
"{\\scriptsize{Matching-Method:Pscore, Base-Year:0,Matching-Interval:0.9-1.10,Log:T,Trim:F}} \n")
add.to.row$command <-comm
print(xtable(industryTable,caption = "Distribution of Privatization Across Manufacturing", label = "table:industry",align = c("c","p{4.5cm}","c","c","|p{4.5cm}","c","c"),digits = c(0,0,0,2,0,0,2)),caption.placement="top", include.rownames = FALSE,add.to.row = add.to.row,hline.after=c(-1, 0))
I need to put and note at the bottom of the table, what I' currently doing is using the add.to.row
add.to.row <- list(pos = list(nrow(industryTable)), command = NULL)
comm <- paste0("\\hline \n \\multicolumn{",dim(industryTable)[2],"}{l}",
"{\\scriptsize{Matching-Method:Pscore, Base-Year:0,Matching-Interval:0.9-1.10,Log:T,Trim:F}} \n")
it works fine, however, I have 7 tables in each 32 versions of data combination need exactly the same note format like the one here, the table content and format are different, but for the 7 tables of a given data combination, the table note is exactly the same,which is "Matching-Method:Pscore, Base-Year:0,Matching-Interval:0.9-1.10,Log:T,Trim:F", is there a convenient way of achieving this without of copy paste, cause it's tedious and dangerous.
Why not just create a function?
make_table <- function(industryTable) {
l = list(pos = list(nrow(industryTable)), command = NULL)
comm <- paste0("\\hline \n \\multicolumn{",dim(industryTable)[2],"}{l}",
"{\\scriptsize{Matching-Method:Pscore, Base-Year:0,Matching-Interval:0.9-1.10,Log:T,Trim:F}} \n")
l$command <-comm
xtable(industryTable,
caption = "Distribution of Privatization Across Manufacturing",
label = "table:industry",align = c("c","p{4.5cm}","c","c","|p{4.5cm}","c","c"),digits = c(0,0,0,2,0,0,2)),
caption.placement="top",
include.rownames = FALSE,
add.to.row = l, hline.after=c(-1, 0)
}
So
print(make_table(industryTable))

knitr xtable highlight and add horizontal lines for the same row,

I am using knitr and xtable to automate my reporting procedure. I want to highlight a few rows of a table and have a horizontal line right above each row highlighted. The .Rnw file I am using reads as below:
\usepackage{colortbl, xcolor}
\usepackage{longtable}
\begin{document}
<<do_table, results = "asis">>=
library(xtable)
mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
print(xtable(mydf), add.to.row = list(pos = list(0,2), command = rep("\\rowcolor[gray]{0.75}",2)),hline.after=c(0,2))
#
\end{document}
This works just fine, however, the table I am working with should be a longtable, if I adjust the last line of code to
print(xtable(mydf), add.to.row = list(pos = list(0,2), command = rep("\\rowcolor[gray]{0.75}",2)),hline.after=c(0,2),tabular.environment="longtable",floating=FALSE)
the output is quite ugly, and the rows are not highlighted as expected. Anyone might know an answer to this question?
thanks,
David
Sorry, slightly offtopic, but demonstrating a markdown-only solution for highlighting cells/rows easily:
> mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
> library(pander)
> emphasize.strong.rows(c(1, 3))
> pander(mydf)
---------------------------
id var1 var2
----- ---------- ----------
**1** **0.7194** **0.6199**
2 0.8094 0.1392
**3** **-1.254** **0.5308**
4 0.4505 0.8235
5 -0.3779 0.7534
6 -0.3518 0.3055
7 1.759 0.5366
8 0.9822 0.9938
9 1.549 0.3589
10 -1.077 0.5153
---------------------------
That can be converted to LaTeX or pdf directly.
You are on the right track, but I am a bit confused: do you want the selected rows highlighted by hline and rowcolor? In my experience, rowcolor alone looks better, so I will assume that in my answer below (but you could easily use both, just append the \\hline command).
As a bonus, all code below assumes you use the LaTeX booktabs package, which gives correctly weighted rules (unlike hline). To be honest, I always work with booktabs, and I couldn't bother to adjust the code to use hline -- but if you prefer hline, replace all \toprule, \midrule and \bottomrule macros with \hline.
You seem to have missed that LaTeX longtables require a special header, and we need to supply that too as an element to the command vector of the add.to.row list (this may be the reason your typeset table looks bad).
longtable.xheader <-
paste("\\caption{Set your table caption.}",
"\\label{tab:setyourlabel}\\\\ ",
"\\toprule ",
attr(xtable(mydf), "names")[1],
paste(" &", attr(xtable(mydf), "names")[2:length(attr(xtable(mydf), "names"))], collapse = ""),
"\\\\\\midrule ",
"\\endfirsthead ",
paste0("\\multicolumn{", ncol(xtable(mydf)), "}{c}{{\\tablename\\ \\thetable{} -- continued from previous page}}\\\\ "),
"\\toprule ",
attr(xtable(mydf), "names")[1],
paste("&", attr(xtable(mydf), "names")[2:length(attr(xtable(mydf), "names"))], collapse = ""),
"\\\\\\midrule ",
"\\endhead ",
"\\midrule ",
paste0("\\multicolumn{", as.character(ncol(xtable(mydf))), "}{r}{{Continued on next page}}\\\\ "),
"\\bottomrule \\endfoot ",
"\\bottomrule \\endlastfoot ",
collapse = "")
With that taken care of, go ahead and print the xtable:
print(xtable(mydf),
floating = FALSE, % since longtable never floats
hline.after = NULL, % hline off since I use booktabs
add.to.row = list(pos = list(-1,
c(0, 2),
nrow(xtable(mydf))),
command = c(longtable.xheader,
"\\rowcolor[gray]{0.75}\n",
"%")), % comments out a spurious \hline by xtable
include.rownames = FALSE, % depends on your preference
include.colnames = FALSE, % depends on your preference
type = "latex",
tabular.environment = "longtable",
% xtable tries to escape TeX special chars, can be annoying sometimes
sanitize.text.function = function(x){x},
% not all dashes are meant to be math negative sign, set according to your data
math.style.negative = FALSE)
I hope my use of booktabs in the answer did not confuse you too much.
Keep knitting!
You might have more luck posting this on a latex forum. You should note that xcolor/longtable are not compatible: http://www.ukern.de/tex/xcolor.html.

Resources