Ali Akbar
Ali Akbar

Reputation: 21

knitr kable horizontal line not appearing in second last line pdf

    library(knitr)
    library(kableExtra)
    df <- data.frame("r1" = c(1,2,3,4), "r2"=c(4,5,6,6), "r3"=c(7,8,9,8), "r4"=c(11,12,13,89))
    kable(df, format = "latex", booktabs = T, linesep = c('','','\\hline'))

actually this code should get a horizontal line at the second last line

But, i am not getting it. Is this a bug in kable or anything else?

I am trying to get a line above the last line for total. I am using Knitr Kable for this and knitting to pdf. Please Help

Upvotes: 2

Views: 2672

Answers (1)

Martin Schmelzer
Martin Schmelzer

Reputation: 23889

As far as I know, this is not how linesep works for kable. Instead you could use xtable:

library(xtable)
df <- data.frame("r1" = c(1,2,3,4), "r2"=c(4,5,6,6), "r3"=c(7,8,9,8), "r4"=c(11,12,13,89))
print(xtable(df), hline.after = c(0,3))

enter image description here


Why it does not work

This is the internal code in kable that produces the linesep:

linesep = if (nrow(x) > 1) {
  c(rep(linesep, length.out = nrow(x) - 2), linesep[[1L]], '')
} else rep('', nrow(x))
linesep = ifelse(linesep == "", linesep, paste0('\n', linesep))

In line 2 you can see that your linesep argument is going to be repeated nrow(x)-2 times. So if you pass linesep = c("", "", "\\hline") to kable and you only have 4 rows, then this vector will be repeated 2 times. But since the vectors length is greater than 2, it only uses the first 2 elements which are empty. At the end of the snippet you have an empty character vector with 4 elements and therefore no horizontal ruler appears.

Upvotes: 1

Related Questions