【问题标题】:How to save and edit the content of a kable print?如何保存和编辑 kable 打印的内容?
【发布时间】:2018-02-06 08:28:50
【问题描述】:

这是how to export a dataframe to latex with some minimal formatting?的后续行动

考虑这个工作示例

```{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))
``` 

给了

\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}

这里我想将此输出写入tex 文件,并手动删除它的第一行和最后一行。

不幸的是,天真

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"

在这里不起作用。有任何想法吗? 谢谢!

【问题讨论】:

  • 假设您正在使用 .Rmd 文件,请参阅保留中间 .tex 文件,您可以手动编辑然后重新编译。 rmarkdown.rstudio.com/…
  • 感谢@meenarapan,但我使用的是常规脚本
  • 所以你的意思是在 R 脚本而不是在你的 tex 文件中手动删除?
  • 我的意思是我想将 tex 表保存到 tex 文件中,同时删除它的第一行和最后一行(带有 begin tabular 和 end tabular 的行)谢谢!

标签: r dplyr latex knitr


【解决方案1】:

当您打印piper 时,您实际上是在调用一个进行大量更改的打印方法。 piper 不仅仅是那 10 行文字。

如果你想得到这些行,你可以调用capture.output(piper),你应该能够将它过滤为一个字符向量。我不认为row_number() 函数适用于这些,但常规索引应该。例如,

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

编辑添加:要打印不带行号的内容,请使用cat()。例如,

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

【讨论】:

  • 非常感谢,但是有一个问题。捕获输出的输出看起来像[1] "" [2] "\\begin{tabular}{llrr}" [3] "\\toprule" [4] "\\multicolumn{2}{c}{Text} &amp; \\multicolumn{2}{c}{Values} \\\\" ...如何在没有行号和额外的`\`的情况下获得正确的tex内容?
  • lines[c(-1, -length(lines))] %&gt;% cat(file="path/to/myfile.tex",sep = "\n")
猜你喜欢
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 2019-03-07
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多