从函数返回 print xtable 包括转义字符 knitr r

returning print xtable from a function includes escaped characters knitr r

下面的 Rmd 代码

---
output:
  pdf_document
---
```{r setup}
library(knitr)
library(xtable)
library(tidyverse)

data <- diamonds %>% head(3) %>% select(carat, cut, color, depth)

make_table <- function(){
  addtorow_comp <- list()
  addtorow_comp$pos <- list(0,0)
  addtorow_comp$command <- c("\multicolumn{3}{c}{all the Cs} & D \\\n",
                               "carat & cut & color & depth \\\n")
    
    tmp <- xtable(data,
                  caption="a table",
                  align = c('l|','c{0.3in}', 'c{0.4in}','c{0.4in}|', 'c{0.4in}|'),
                  digits= c(0,0,0,0,1))
    
  return(print(tmp, add.to.row = addtorow_comp, 
                         include.colnames = FALSE, 
                         rotate.colnames = FALSE, 
                         include.rownames = FALSE,
                         type="latex"))
}
tbl_to_output <- make_table()
```

```{r output_table, results="asis", cache=FALSE}
tbl_to_output

```

tbl_to_output 输出包含转义字符的文本的乳胶,例如\\ 表示单斜线,\n 表示换行符。如果我直接从 output_table 块 运行 打印命令,它工作正常,但我想将 table 的构建与它们显示的位置分开。

期望的输出:

从函数返回时的输出:

我添加了一些更正和评论,现在可以使用了:

---
output:
  pdf_document
---

```{r setup, results='asis', echo=FALSE, include=FALSE}
library(knitr)
library(xtable)
library(tidyverse)

data <- diamonds %>% head(3) %>% select(carat, cut, color, depth)

make_table <- function(){
  addtorow_comp <- list()
  addtorow_comp$pos <- list(0,0)
  addtorow_comp$command <- c("\multicolumn{3}{c}{all the Cs} & D \\\n",
                               "carat & cut & color & depth \\\n")
    
    tmp <- xtable(data,
                  caption="a table",
                  align = c('l|','c@{0.3in}', 'c@{0.4in}','c@{0.4in}|', 'c@{0.4in}|'), #don't forget about @
                  digits= c(0,0,0,0,1))
    
  return(print(tmp, add.to.row = addtorow_comp, 
                         include.colnames = FALSE, 
                         rotate.colnames = FALSE, 
                         include.rownames = FALSE,
                         type="latex", 
                         table.placement="H", 
                         comment=FALSE)) #hold pos and no comments
}

#tbl_to_output <- make_table()
```


```{r xtable, results='asis', echo=FALSE, message=FALSE}
tbl_to_output <- make_table()
```

补充:

你也可以这样操作:

\begin{figure}
`r tbl_to_output`
\end{figure}