R语言 如何将'kable'输出转换为字符

gr8qqesn  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(172)

我想把R中的不同字符串合并到同一个数组中,就像我在下面的例子中所做的那样:

c("Hello",u,"world")

其中u应该是knitr包中kable()函数的结果。

pmatrix <- function(x) {
  cat(c("\\begin{equation*}\n",
    "\\left(",
    knitr::kable(x, format = "latex", 
                 tabular = "array",
                 vline = "",
                 align = "c",
                 linesep = "",
                 toprule = NULL,
                 bottomrule = NULL),
    "\n\\right)\\, .\n",
    "\\end{equation*}\n"))
}

x <- structure(c(6, 4, 3, 1, 6, 2, 5, 3, 5, 3, 6, 0, 6, 0, 5, 5), dim = c(4L, 
                                                                          4L))

pmatrix(x)
#> \begin{equation*}
#>  \left( 
#> \begin{array}{cccc}
#> 6 & 6 & 5 & 6\\
#> 4 & 2 & 3 & 0\\
#> 3 & 5 & 6 & 5\\
#> 1 & 3 & 0 & 5\\
#> \end{array} 
#> \right)\, .
#>  \end{equation*}

我想在u中转换pmatrix结果的字符。(原因是我想将结果打印到txt文件)

wgeznvg7

wgeznvg71#

您需要删除pmatrix()中的cat()

pmatrix <- function(x) {
  c("\\begin{equation*}\n",
        "\\left(",
        knitr::kable(x, format = "latex", 
                     tabular = "array",
                     vline = "",
                     align = "c",
                     linesep = "",
                     toprule = NULL,
                     bottomrule = NULL),
        "\n\\right)\\, .\n",
        "\\end{equation*}\n")
}

x <- structure(c(6, 4, 3, 1, 6, 2, 5, 3, 5, 3, 6, 0, 6, 0, 5, 5), dim = c(4L, 
                                                                          4L))
pmatrix(x)
#> [1] "\\begin{equation*}\n"                                                                                            
#> [2] "\\left("                                                                                                         
#> [3] "\n\\begin{array}{cccc}\n6 & 6 & 5 & 6\\\\\n4 & 2 & 3 & 0\\\\\n3 & 5 & 6 & 5\\\\\n1 & 3 & 0 & 5\\\\\n\\end{array}"
#> [4] "\n\\right)\\, .\n"                                                                                               
#> [5] "\\end{equation*}\n"

创建于2023年2月13日,使用reprex v2.0.2

相关问题