2

I am trying to create a table with a numeric column number which I wish to center and flushright content as follows:

enter image description here

Using RMarkdown, I am only able to wrap LaTeX code around/inline with cell content in R using the paste0() as follows, and I am not able to modify the LaTeX tabular environment:

i.e. table$number <- paste0("\\begin{centering}", table$number, "\\end{centering})

So possible ways to approach this is to use eqmakebox or multicol or varwidth. But my surficial understanding of these commands have not made possible of what I want.

The table in LaTeX as a reproducible example:

\begin{tabu} to \linewidth {>{\centering}X>{\raggedleft}X}
\hline
\multicolumn{1}{c}{name} & \multicolumn{1}{c}{number}\\
\hline
a & 10\\           % please only make
\hline
bb & 193048\\      % edits in these 
\hline
ccc & 200\\        % lines so I can reproduce in R
\hline
\end{tabu}

SO posting with more flavours of R in it

  • What about changing each table line to a & \multicolumn{1}{c}{10}\\ , i.e. using table$number <- paste0("\multicolumn{1}{c}{", table$number, "}") Did I understand correctly? – Ondrian Mar 28 at 2:52
1

mwe

---
output:
  pdf_document: 
    keep_tex: yes
header-includes:
- \usepackage{booktabs}
---

\tabcolsep3em

```{r,echo=F}
library(knitr)
library(kableExtra)
df <- data.frame(name=c("a","bb","ccc"), number=c(10,193048,200))
kable(df,"latex", align="lr", booktabs = T, linesep = "") %>%
  kable_styling() %>%
  column_spec(1, width = "3em") %>%
  column_spec(2, width = "3em")
```

```{r,echo=F,results='asis'}
library(xtable)
options(xtable.comment = F)
print(xtable(df,digits=0,align="llr"), include.rownames=F,booktabs=T)
```
  • Thank you @Fran. I was able to center the ‘Number’ column with Kable package. However, any idea how to also flush right the numbers? (As seen in the image from the post) And that is great you are using Kable method as I’ve written lots of codes in kableExtra package and hope not to switch package – Jane Mar 28 at 14:28
  • @Jane Answer changed. Is it ok now? – Fran Mar 29 at 7:19
  • that is beautiful thank you! Would you be OK if I answer the same question on StackOverflow with your method? Alternatively, I'll let you post and mark it as the answer. – Jane Mar 29 at 17:43
  • @Jane You're welcome. Feel free to answer yourself the other question. – Fran Mar 29 at 22:30
  • what is your insight on columns with long names, with the column width specification, the long names get squished -- Is there a way I can only customise the rows below the columns? There is no width argument in row_spec(). If not, this is already great! – Jane Mar 30 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.