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

1

5

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!

Transubstantiate answered 29/8, 2017 at 2:7 Comment(4)
Assuming you are working in a .Rmd file, see this on keeping the intermediate .tex file, which you can edit manually and then recompile. rmarkdown.rstudio.com/…Aniconic
thanks @meenarapan but I am using a regular scriptAffairs
So you mean remove manually within the R script rather than in your tex file?Aniconic
I just mean I want to save the tex table to a tex file, while removing its first and last line (the ones with begin tabular and end tabular) thanks!Affairs
M
7

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")
Menashem answered 29/8, 2017 at 11:36 Comment(2)
thanks that very nice but there is a problem. The output of capture output looks like [1] "" [2] "\\begin{tabular}{llrr}" [3] "\\toprule" [4] "\\multicolumn{2}{c}{Text} & \\multicolumn{2}{c}{Values} \\\\" ... how to obtain the proper tex content without the line number and the extra `\` ?Affairs
lines[c(-1, -length(lines))] %>% cat(file="path/to/myfile.tex",sep = "\n")Kevakevan

© 2022 - 2024 — McMap. All rights reserved.