2

I am having a dataframe with both character and numeric columns. I am trying to center the character column (which is done) and (I don't know how to) center flushed-right numeric column. Further, both column names are centered: desired look

Some relevant posts (this and this), but I couldn't incorporate the techniques (if relevant) to my code.

The following code produces the table below:

df <- data.frame(name = c("a", "bb", "ccc"), number = c(10, 193048, 200))

kable(df, format="latex", align = c("c", "r")) %>% 
  kable_styling(full_width = TRUE) %>% 
  row_spec(0, align = "c")

current look

I understand that I can use LaTeX code to produce a single user-customised table. But I need the example to be reproducible in Rmd (imagine I have lots of df) and therefore need to specify within kable().

Should I modify the LaTeX table environment (i.e. \begin{tabu} to \linewidth {>{\centering}X>{\centering}X}) and if so how in R, or use something like multirow to customise the second column??

Jane
  • 579
  • 5
  • 17
  • My answer [here](https://stackoverflow.com/questions/41365502/aligning-columns-with-knitr-kable-function/41365608#41365608) might be relevant. It doesn't use Latex directly, though. – lmo Mar 27 '19 at 00:28
  • Thank you @Imo, I may have missed it, but I didn't see any info on center *and* right alignment for the column. – Jane Mar 27 '19 at 00:36
  • This combo does not appear to be possible directly in `kable`. You may be able to fake it using `sprintf` with the proper formatting, ie adding enough blank spaces to get it to look good enough. Take a look at the examples in the manual page if you want to give that a try. Alternatively, there are a number of alternative table functions, `xtable`, and something in `hmisc`, also the package `tables`. Good luck. – lmo Mar 27 '19 at 00:49
  • 1
    Will give these options a try! – Jane Mar 27 '19 at 20:23

1 Answers1

1

Thanks to @Fran from this post, answer below:

df <- data.frame(name = c("a", "bb", "ccc"), number = c(10, 193048, 200))

kable(df,"latex", align="cr", booktabs = T, linesep = "") %>%
  kable_styling() %>%
  column_spec(1, width = "3em") %>%
  column_spec(2, width = "3em")

Jane
  • 579
  • 5
  • 17