Skip to contents

knitr::kable takes column alignments as a single string, such as "llrrrr" for a table with 2 left-aligned columns followed by 4 right-aligned ones. This function is a quick utility for creating these strings programmatically by the number of left- or right-aligned columns, and/or by calculating column counts on the fly. It makes some assumptions, such as that all left-aligned columns come first, then all right-aligned ones; that's a very common case I developed this for, but your mileage may vary. Out of the 3 arguments (left, right, or total), you need to supply 2.

Usage

align_cols(l = NULL, r = NULL, total = NULL)

Arguments

l

Number of left-aligned columns. Default: NULL

r

Number of right-aligned columns. Default: NULL

total

Total number of columns. Default: NULL

Value

A string that can be passed to knitr::kable, or any other function that takes alignments in the same format.

See also

Examples

# self_rated_health has 3 categorical columns and one numeric column,
# so traditionally this would be formatted in a table with 3 left-aligned
# columns and 1 right-aligned column.
align_cols(l = 3, r = 1)
#> [1] "lllr"

# I might also want to do this on the fly in a number of ways:
align_cols(l = 3, total = ncol(self_rated_health))
#> [1] "lllr"
# maybe a little risky if you don't know the data
align_cols(
    r = sum(sapply(self_rated_health, is.numeric)),
    total = ncol(self_rated_health)
)
#> [1] "lllr"
# For programming this can be useful after reshaping
n_responses <- length(levels(self_rated_health$response))
health_wide <- tidyr::pivot_wider(self_rated_health,
    id_cols = group, names_from = response
)
alignment <- align_cols(r = n_responses, total = ncol(health_wide))
if (require("knitr")) {
    knitr::kable(health_wide, align = alignment)
}
#> Loading required package: knitr
#> 
#> 
#> |group       | Excellent| Very good| Good| Fair| Poor|
#> |:-----------|---------:|---------:|----:|----:|----:|
#> |Connecticut |      0.19|      0.34| 0.29| 0.14| 0.04|
#> |Male        |      0.20|      0.34| 0.29| 0.13| 0.04|
#> |Female      |      0.18|      0.34| 0.29| 0.16| 0.04|
#> |Nonbinary   |      0.09|      0.20| 0.37| 0.22| 0.12|