patyk11
patyk11

Reputation: 11

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

I want to create htmlTables from all the files in the given directory and display them in R markdown.

However when i try to use htmlTable in the for loop there is no output. Here is the code:

``{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])

```

output of the code:

enter image description here

The best solution I was able to come up with is, to write the output of the htmlTable into a List htmlList and diplay the Tables one by one using asis_output(). But this also does not work in a loop.

# 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')

It may work if there are one or two tables. But I need it to work independently of the number of the files.

Here is also a reproducible example :

# 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)

Upvotes: 0

Views: 2399

Answers (1)

lukeA
lukeA

Reputation: 54237

Try it like this:

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

I.e. wrap htmlTable within the for loop in print, and use the chunk option results='asis', which writes raw HTML results (in this case) from R into the output document.

Upvotes: 1

Related Questions