简体   繁体   English

将 kable 乳胶桌重新包装到不同的表格环境

[英]rewrapping kable latex table to different tabular environment

I would like to keep just the "inside" lines of a latex table created by kable.我只想保留 kable 创建的乳胶桌的“内部”线条。 I only know cumbersome and ugly ways to do so...attempts at cleaner versions failed.我只知道这样做的麻烦和丑陋的方法......更清洁版本的尝试失败了。 here is one clean flunk:这是一个干净的不及格:

kable.rewrap <- function( df, newname= "mytable" ) {
    kt <- kable( df, "latex", booktabs=T )
    notop <- strsplit(kt, "\\midrule")[[1]][2]
    nosur <- strsplit(notop, "\\bottomrule" )[[1]][1]  ## fails: doesn't like "\\"!
    newkt <- paste0("\\begin{", newname, "}", nosur, "\n\\end{",newname,"}\n")
    ## attr(newkt, "format") <-  chr "latex"  # wrong
    newkt
}

print(kable.rewrap( data.frame( x=1:3, y=1:3 ), "mytable" ))

should produce应该产生

\begin{mytable}
\toprule
x & y\\
\midrule
1 & 1\\
2 & 2\\
3 & 3\\
\bottomrule
\end{mytable}

obviously, my latex code should define an environment mytable now.显然,我的乳胶代码现在应该定义一个环境mytable I am also puzzled by "bottomrule" in the nosur line works, but "\\\\bottomrule" fails.我也对nosur系列作品中的“bottomrule”感到困惑,但“\\\\bottomrule”失败了。

(another alternative is to forego kable altogether and just work with the data frame, separating each line by a \\ and each column by a &.) (另一种选择是完全放弃 kable,只使用数据框,用 \\ 分隔每一行,用 & 分隔每一列。)

advice appreciated.建议表示赞赏。

1) The kable.envir argument will add the mytable part but that still causes tabulars to be generated which we remove using gsub : 1) kable.envir参数将添加mytable部分,但这仍然会导致生成表格,我们使用gsub删除它:

kable(test_data, "latex", booktabs = TRUE, table.envir = "mytable") %>%
  gsub(".(begin|end){tabular.*}", "", ., perl = TRUE)

giving:给予:

\begin{mytable}


\toprule
x & y\\
\midrule
1 & 1\\
2 & 2\\
3 & 3\\
\bottomrule

\end{mytable}

2) Another possibility is to define your own mytabular environment and then use: 2)另一种可能是定义自己的mytabular环境,然后使用:

kable(test_data, "latex", booktabs = TRUE, table.envir = "mytable") %>%
  kable_styling(latex_table_env = "mytabular")

which gives:这使:

\begin{mytable}

\begin{mytabular}{rr}
\toprule
x & y\\
\midrule
1 & 1\\
2 & 2\\
3 & 3\\
\bottomrule
\end{mytabular}
\end{mytable}

Added添加

In (2) rather than defining a do-nothing environment to replace tabular tex/latex actually makes one available already, namely @empty .在 (2) 中,而不是定义一个什么都不做的环境来替换 tabular tex/latex 实际上已经提供了一个可用的环境,即@empty

kable(test_data, "latex", booktabs = TRUE, table.envir = "mytable") %>%
  kable_styling(latex_table_env = "@empty")

Note笔记

We named the data frame shown in the question as follows:我们将问题中显示的数据框命名如下:

test_data <- data.frame(x = 1:3, y = 1:3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM