I am performing a simple task: creating a table and outputting it using R Markdown
to pdf
as follows:
library(knitr)
kable(datatable,align='ccccccc',
col.names = c("Copy","Sigma Est","Sigma Lower","Sigma Upper",
"Lambda Est","Lambda Lower","Lambda Upper"),digits=3)
Problem
when I output the table, columns are not centered. Actually, for some tables they are right aligned for others - left aligned, which seems rather random to me.
Question
How can I control the alignment of columns with R
function kable
from package knitr
, i.e., what am I doing wrong?
EDIT
Running:
library(knitr)
kable(datatable,align=c(rep('c',times=7)),
col.names = c("Copy","Sigma Est","Sigma Lower","Sigma Upper",
"Lambda Est","Lambda Lower","Lambda Upper"),digits=3)
Yields:
| Copy | Sigma Est | Sigma Lower | Sigma Upper | Lambda Est | Lambda Lower | Lambda Upper |
|:----:|:---------:|:-----------:|:-----------:|:----------:|:------------:|:------------:|
| 0 | 14.631 | 12.275 | 16.987 | 0.129 | 8.778 | 9.296 |
| 1 | 16.988 | 14.275 | 19.700 | 0.136 | 8.190 | 8.736 |
| 2 | 20.850 | 17.517 | 24.183 | 0.129 | 8.595 | 9.113 |
| 3 | 20.551 | 17.229 | 23.874 | 0.127 | 9.015 | 9.523 |
| 4 | 22.651 | 18.993 | 26.310 | 0.127 | 8.969 | 9.478 |
| 5 | 23.369 | 19.652 | 27.086 | 0.127 | 8.599 | 9.108 |
This is exactly what I want as :---:
denotes centering of columns, however, when I press Knit PDF
and a pdf
document is produced, all columns are still left-aligned. How do I go around that?
You want to feed
kable
a vector of alignment strings equal to the number of columns. As mentioned in the help file,Here is a reproducible example.
Without any alignment values, character columns are left-aligned and numeric columns are right-aligned as you can see below.
which returns
To get the numeric columns center-aligned, while keeping the character column right aligned, I used the following.
The following text, if copied into an .Rmd file, will return the table, formatted as desired as a pdf file.