R Markdown 和 htmlTable。如何在 R Markdown 中循环生成 html 表?

R Markdown and htmlTable. How to generate html tables in a loop in R Markdown?

我想从给定目录中的所有文件创建 htmlTables 并在 R markdown 中显示它们。

然而,当我尝试在 for 循环中使用 htmlTable 时,没有输出。这是代码:

``{r }
path<-"~/wyniki stocks"

listFiles<-as.list(list.files(path))

for(file in listFiles){

################################  
 #Generating path to the current file 
path1<-paste(path,"/",file, sep="")
print(path1)

#############################
#Reading File
output<-read.dta(path1)


######################################
#html table
htmlTable(output[1:2,1:2])

}



print("Why are there no tables above?")


htmlTable(output[1:2,1:2])

```

代码输出:

我能想到的最佳解决方案是,将 htmlTable 的输出写入列表 htmlList 并使用 asis_output() 一个一个地显示表格。但这在循环中也不起作用。

# Does not work, htmlList is a list  
htmlList[i]<-htmlTable(output[1:2,1:2]) 
for(i in 1:10)
asis_output(htmlList[i],meta='html')

#works
asis_output(htmlList[1],meta='html')
asis_output(htmlList[2],meta='html')
asis_output(htmlList[3],meta='html')

如果有一个或两个表,它可能会起作用。 但我需要它独立于文件数量工作。

这也是一个可重现的例子:

# Preparing data

{r}
library(htmlTable)
library(knitr)
output <- matrix(1:4,
                 ncol=2,
                 dimnames = list(list("Row 1", "Row 2"),
                                 list("Column 1", "Column 2")))


# Part 1

{r}
htmlTable(output)


# Part 2
{r}
for(i in 1)
  htmlTable(output)

像这样尝试:

```{r, results='asis'}
for(i in 1)
  print(htmlTable(output))
```

即在 printfor 循环中包装 htmlTable,并使用块选项 results='asis',它将 R 中的原始 HTML 结果(在本例中)写入输出文档。