Here is the task: **how to append two tables using R Markdown? **The need arose because
I was demonstrating to graduate students in a research methods course how to
prepare Table 1, which often covers descriptive statistics in an empirical
paper.

I used tableone package in R to compute the summary statistics. The task was to replicate the
first table from Prof. Daniel Hamermesh’s paper that explored whether
instructors’ appearance and looks influenced the teaching evaluation score
assigned by the students. Since Prof. Hammermesh computed some summary
statistics using weighted data, such as weighted mean and weighted standard
deviations, and non-weighted data using regular means and standard deviations, I relied on
two different commands in tableone to compute summary statistics.

The challenge was to combine the output from the two tables into one table. Once I generated the two tables separately, I used kables() and list() options to generate the appended table. I needed knitr and kableExtra packages to format the table. Here is how the apended looks.

Here are
the steps involved.

Assume that you have two tables generated by either svyCreateTableOne or
CreateTableOne commands. Let’s store the results in objects tab1 and tab2.

In R Markdown using RStudio, print the tables to objects named
arbitrarily as p and p1. See the code below. The results=’hide’ is needed if
you do not want to see the tables outputted in the draft as text.

```{r, echo=FALSE, results='hide'}

p <- print(tab1)

p2 <-print(tab2)

```

The
amalgamated table used the following script. Note some import considerations.

- I used bottomrule=NULL to suppress the horizontal line for the table on the top.
- I used column_spec(1, width = '1.75in') for both tables so that the second and subsequent columns lineup vertically. Otherise, they will appear staggered.
- I used col.names = NULL to suppress column names for the bottom table because the column names are the same for both tables.
- I used column_spec(5, width = '.7in') to ensure that the horizontal lines drawn for the bottom table match the width of the horizontal line on top of the first table.
- I used kable_styling(latex_options = "HOLD_position") to ensure that the table appears at the correct place in the text.

```{r,
echo=FALSE}

kables(

list(

kable(p, booktabs=TRUE, format = "latex",valign='t', bottomrule=NULL) %>%

column_spec(1, width = '1.75in'),

kable(p2, booktabs=TRUE, format = "latex", valign='t', col.names = NULL) %>%

column_spec(1, width = '1.75in') %>%

column_spec(5, width = '.7in')),

caption="Weighted and unweighted data") %>%

kable_styling(latex_options = "HOLD_position")

```

## No comments:

## Post a Comment