Search code examples
rlatexcharacter

How to convert the `kable` output in characters


I would like to merge different strings in R in the same array like I'm doing e.g. in the following example:

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

where u should be the result of kable() function in knitr package. Anyway

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

I would like to have in u the conversion in character of the pmatrix result. (The reason is because I would like to then print the result to a txt file)


Solution

  • You need to remove the cat() in pmatrix():

    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"
    

    Created on 2023-02-13 with reprex v2.0.2