Basic Table Example

Author
Affiliation

Beau B. Bruce, MD, PhD

Emory University

Introduction

Herein a table is presented that would be suitable for inclusion in the final project or to be used in a manuscript.

The table creation process involves some data manipulation, but most importantly the data is formatted for presentation in a document, e.g., with a reasonable number of decimal places.

I will demonstrate using the builtin iris dataset which hase data on iris flower measurements (sepal length, sepal width, petal length, petal width) for three species of iris flowers.

I’ll create a summary table with means and standard deviations for each of the four measurement variables, stratified by species, using the techniques we used in the earlier exercise. But I will also show you how to do the same thing using tidyverse functions.

Ok, let’s load the tidyverse package and the iris dataset.

Take a look at what iris looks like before we summarize it.

Now, let’s create two helper functions to format means and standard deviations for our tables.

Create the summary table without tidyverse

Now let’s create the summary table without using tidyverse functions and without some more advanced base R programming techniques we will learn later.

Let’s split the data.frame into three data.frames, one per species using a for loop.

Use our helper functions to create summary tables for each species and using some loops to simplify our work a bit (and make it less error prone)

Let’s cbind these three summary tables together to create one big table. Although cbind is usually not recommended, it works fine here because we know that the rows are in the same order and we just want to present them side by side so that we can construct our table vs. use this data for subsequent analysis.

Perfect! Now, let’s make it into HTML without the first column, so it’s easy to copy and paste into our Word table shell.

Create the summary table with tidyverse

Is it easier to make? Not necessarily. I needed to experiment quite a bit to get what I wanted and had to rely on help files considerably even though I have substantial familiarity with the tidyverse ecosystem. Instead of a core set of base functions that you can mix and match, you need to be familiar with the spectrum of tidyverse verbs and their usage and default parameters, including functions like across, separate, and pivot_wider that are quite tricky to get right. Once you have it right though, it is quite easy to read and understand.

To create the table “meat” as we did above, we can just feed that directly into knitr::kable.