2
    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

zx8754
  • 52,746
  • 12
  • 114
  • 209
Ali Akbar
  • 21
  • 3

1 Answers1

1

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.

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • https://stackoverflow.com/questions/45409750/get-rid-of-addlinespace-in-kable I had the issue of linesep in every fifth line by default. I saw this article and knew how the logic in which linesep works. https://github.com/yihui/knitr/blob/master/R/table.R Also, 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')) – Ali Akbar Nov 24 '17 at 04:32
  • 1
    So, you are saying to drop kable. – Ali Akbar Nov 24 '17 at 04:49
  • Added some explanation. As far as I am concerend I would use xtable instead. For this case it delivers more flexibility. – Martin Schmelzer Nov 24 '17 at 13:50