How to save and edit the content of a kable print?

落爺英雄遲暮 提交于 2019-12-07 10:39:16

问题


This is a follow-up to how to export a dataframe to latex with some minimal formatting?

Consider this working example

```{r table, results='asis'}
library(knitr)
library(kableExtra)
library(magrittr)

dataframe <- data.frame(mytext1 = c('HELLO',
                                   'WORLD'),
                        mytext2 = c('HELLO',
                                   'AGAIN'),
                        value1 = c(1,2), 
                        value2 = c(1,2))

piper <- dataframe %>%
    kable(format = 'latex', booktabs = TRUE) %>%
    add_header_above(header = c("Text" = 2, "Values" = 2))
``` 

which gives

\begin{tabular}{llrr}
\toprule
\multicolumn{2}{c}{Text} & \multicolumn{2}{c}{Values} \\
\cmidrule(l{2pt}r{2pt}){1-2} \cmidrule(l{2pt}r{2pt}){3-4}
mytext1 & mytext2 & value1 & value2\\
\midrule
HELLO & HELLO & 1 & 1\\
WORLD & AGAIN & 2 & 2\\
\bottomrule
\end{tabular}

Here I would like to write this output to a tex file, and remove manually the first and last line of it.

Unfortunately, the naive

piper  %>% filter(row_number() >=2 & row_number() <=(length(piper) - 1))
Error in UseMethod("filter_") : 
  no applicable method for 'filter_' applied to an object of class "knitr_kable"

does not work here. Any ideas? Thanks!


回答1:


When you print piper, you're actually calling a print method which makes a lot of changes. piper isn't just those 10 lines of text.

If you want to get those lines, you can call capture.output(piper), and you should be able to filter that as a character vector. I don't think the row_number() function works on those, but regular indexing should. For example,

lines <- piper  %>% capture.output
lines[c(-1, -length(lines))]

Edited to add: To print that without line numbers, use cat(). For example,

lines[c(-1, -length(lines))] %>% cat(sep = "\n")


来源:https://stackoverflow.com/questions/45929671/how-to-save-and-edit-the-content-of-a-kable-print

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!