Can I have two summary statistics in one cell in R-generated LaTex tables? I'm using the tables package and I'd like to summarize a column as mean (sd). Here's a reproducible example in rmarkdown.
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tables)
library(dplyr)
```
```{r table, results='asis'}
seed <- 1
iris2 <- iris %>% mutate(Region = factor(sample(c('East', 'West', 'Central'), 150, replace = TRUE)))
tabular((Species + 1) ~ (Region + 1) * Sepal.Length * (mean + sd),
data = iris2) %>%
latex %>%
print
```
The output looks like this:
But I want the cells to look like e.g. 5.037 (0.3041). Is that possible?
You can probably do something you want using paste()
E.g.:
paste(round(mean[1], digits=3), "(", sd[1], ")", collapse="")
The Paste pseudo-function does the trick, but introduces unnecessary padding (see: Remove padding from pasted cells in LaTex, R). Example code:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tables)
library(dplyr)
```
```{r table, results='asis'}
seed <- 1
iris2 <- iris %>% mutate(Region = factor(sample(c('East', 'West', 'Central'), 150, replace = TRUE)))
tabular((Species + 1) ~ (Region + 1) * Sepal.Length * Paste(Percent(), length, sep = '\\% (', postfix = ')'),
data = iris2) %>%
latex %>%
print
```
Related
I am using knitr::kable to print my dataframes, but sometimes they are too big. Is there any simple way to print them compactly with scrollbar?
For example, I do:
knitr::kable(mtcars)
How could I add scrolling by condition (for example, if nrow > 10 and/or ncol > 10)?
P.S. DT::datatable doesn't work for big ncol:
I need exactly scrolling interface.
You can add scrollbars. For example, with kableExtra or DT:
R Markdown
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
```
Some very wide data:
```{r}
df <- cbind(mtcars, mtcars)
```
With `kableExtra`:
```{r}
kable(df) %>%
kable_styling("striped", full_width = F) %>%
scroll_box(width = "100%", height = "200px")
```
Or with `DT`:
```{r}
DT::datatable(
df,
height = 200,
options = list(scrollX = TRUE)
)
```
output
I am trying to produce a well formatted contingency table in an rmarkdonw html document. Here is the code:
---
title: "Probabilidad"
author: "Nicolás Molano Gonzalez"
date: "7 de Abril de 2020"
output:
html_document:
fig_caption: true
---
```{r echo=F, message = FALSE, warning =F}
library(tidyverse)
library(kableExtra)
library(knitr)
set.seed(150)
```
this the data for the table:
```{r echo=FALSE, results = 'asis'}
ca_ctr_r<-.3
n <- 250
nCA <- round(n*ca_ctr_r)
z0 <- data.frame(status=c(rep("CA",nCA),rep("CTR",n-nCA)))
z0$exposition <- NA
exp_CA <- .45
exp_CTR <- .19
z0[z0$status %in% "CA","exposition"] <- ifelse(runif(nCA) < exp_CA,"yes","no")
z0[z0$status %in% "CTR","exposition"] <- ifelse(runif(n-nCA) < exp_CA,"yes","no")
z0$exposition <- factor(z0$exposition,levels = c("yes","no"))
```
here is the code to print the contingency table, which should be improved.
```{r echo=FALSE, results = 'asis'}
res <- kable(t(table(z0)%>%addmargins))
#res <- kable(t(table(z0)))
kable_styling(res,"striped", position = "center",full_width = F) %>% add_header_above(c("exposition","status"=2," "))
```
I want the output of the code to be similar to that of base R namely:
status
exposition CA CTR Sum
no 40 96 136
yes 35 79 114
Sum 75 175 250
add_header_above lets me get the title for the columns but I am struggling to achieve the title for the rows (exposition) in the right position.
I tried a workaround by explicitly adding a column to the left of the table before passing it to kable.
library(tidyverse)
library(kableExtra)
library(knitr)
cont.table = mtcars %>% select(gear, carb) %>%
group_by_all() %>% tally() %>%
spread(key = gear, value = n)
cont.table %>%
rename("\t" = carb) %>%
add_column(" " = c("carb", rep(" ", nrow(.) - 1)), .before = "\t") %>%
kable() %>%
kable_styling(position = "left", full_width = F, ) %>%
add_header_above(c("", "", "gear", rep(" ", ncol(cont.table) - 2))) %>%
column_spec(1:2, bold = TRUE)
---
output:
word_document: default
---
```{r setup, include=FALSE}
data("mtcars")
library(tidyverse)
library(xtable)
library(sjPlot)
library(kableExtra)
```
```{r, results='asis'}
df <- mtcars %>%
group_by(cyl) %>%
summarise(disp = mean(disp),
wt = mean(wt),
n = n()
)
kable(df)
# tab_df(df)
# xtable(df)
```
I have tried xtable, tab_df, and kable to generate a word document with a table. When "knit to HTML document", all tables looked fine. When "knit to Word", xtable didn't show the table while tab_df and kable produced a table with only one column:
kable(df)
cyl
disp
wt
n
4
105.1364
2.285727
I experimented with flextable quite a bit the last few days and it might be the best option when you have to work with Word:
---
output:
word_document: default
---
```{r setup, include=FALSE}
data("mtcars")
library(tidyverse)
library(flextable)
```
```{r, results='asis'}
mtcars %>%
group_by(cyl) %>%
summarise(disp = mean(disp),
wt = mean(wt),
n = n()
) %>%
flextable() %>%
align(part = "all") %>% # left align
set_caption(caption = "Table 1: Example") %>%
font(fontname = "Calibri (Body)", part = "all") %>%
fontsize(size = 10, part = "body") %>%
# add footer if you want
# add_footer_row(values = "* p < 0.05. ** p < 0.01. *** p < 0.001.",
# colwidths = 4) %>%
theme_booktabs() %>% # default theme
autofit()
```
Consider this simple example
---
title: "Untitled"
output:
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
options(knitr.table.format = "latex")
```
## Slide with R Output
```{r , echo = FALSE ,warning = FALSE}
library(knitr)
library(kableExtra)
library(dplyr)
cars %>%
filter(dist < 5) %>%
kable('latex', booktabs = T, escape = F, col.names = c( "$\\alpha$" , "$\\beta$" ) ) %>%
kable_styling(latex_options = c("striped", "hold_position"),
full_width = T)
```
Now this correcly generates the following output
The issue is that the renaming in col.names is manual and very tedious when my dataframe has many columns.
I would like to be able to able to say " if you see this variable dist in the dataframe, then map it to $\alpha$. Otherwise leave as is.
How can this be done?
Note, I am rendering the file using rmarkdown::render()
Thanks!!
I'm trying to fit large table of frequencies into my slide. There are many values, and even the rare ones would be nice to show.
I played with different options but none gives me a satisfactory solution. Here is Rmd so far:
---
title: "Untitled"
author: "author"
date: "date"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
df <- as.data.frame(table(rownames((USArrests))))
```
## table 1
```{r t1, echo = TRUE}
table(rownames((USArrests)))
```
## table 2
```{r t2}
library(knitr)
library(kableExtra)
kable(df, "html") %>%
kable_styling(bootstrap_options = "striped", font_size = 10)
```
Table 1 doesn't fit:
Table 2 could be squeezed but with tiny font, and lots of wasted space on the sides.
I also looked into pander, xtable and stargazer but failed to find solution from them either.
Any other alternatives?
You could spread your table across multiple columns to fit the space. In my example below, I split the frame up into 3 pairs of columns with uneven length.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library(dplyr)
library(magrittr)
library(knitr)
library(kableExtra)
```
## table 1
```{r, echo=TRUE, eval=FALSE}
USArrests %>% rownames %>% table
```
```{r, echo=FALSE}
df <- USArrests %>%
rownames %>%
table %>%
as_tibble
df %$%
tibble(
name1 = `.`[1:17],
n1 = n[1:17],
name2 = `.`[18:34],
n2 = n[18:34],
name3 = c(`.`[35:50], ""),
n3 = c(n[35:50], "")
) %>%
kable("html", align = c("l", "c"), col.names = rep(c("Name", "Frequency"), 3)) %>%
kable_styling(bootstrap_options = c("striped", "condensed"), font_size = 18)
```
N.B. I accept the transform step into multiple columns could have been done more elegantly and providing and more programmatic solution, however, I'll leave that to others to refine.