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!
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With