Rmarkdown 打印 data.frame 内部函数

Rmarkdown printing data.frame inside function

我使用 iris data.frame 简化了我的问题。问题是我无法在 Rmd 文件中的函数内打印 data.frame。

这是我的 "test.Rmd" 文件:

```{r results='asis',echo=FALSE}  
fun_test<-function(dfiris){
  out<-tryCatch(
    { 
      cat("  \n### Inside fun_test. Printing dfiris -> FAIL  \n")
      cat("  \n")
      kable(dfiris) # It does not work
    },
    error=function(cond){return(NA) }    
  )
}
```

```{r results='asis',echo=FALSE}  
library(knitr)
df1<-head(iris)
cat("  \n## Start. Outisde fun_test. Printing df1 -> OK  \n")
cat("  \n")
kable(df1)
fun_test(df1)
```

因此,我将其呈现为 Word 文档:

render("test.Rmd","word_document")

输出是:

为什么data.frame "dfiris" 没有打印出来?我的 "fun_test" 功能有问题吗?

您没有 return 结果,只是将其分配给 out

尝试:

fun_test<-function(dfiris){
  tryCatch(
    { 
      cat("  \n### Inside fun_test. Printing dfiris -> FAIL  \n")
      cat("  \n")
      kable(dfiris) # It does not work
    },
    error=function(cond){return(NA) }    
  )
}