How to view html in R-Studio?

Viewed 1124

In R-Studio, I am running the code from this website: https://cran.r-project.org/web/packages/ztable/vignettes/heatmapTable.html, specifically the code below.

 install.packages("ztable")
 if(!require(devtools)) install.packages("devtools")
 devtools::install_github("cardiomoon/ztable")
 require(moonBook)
 x=table(acs$Dx,acs$smoking)
 library(ztable)
 library(magrittr)
 options(ztable.type="html")
 z=ztable(x) 
 print(z,caption="Table 1. Basic Table")

I expected to see the table in the R-Studio Plot or Viewer pane, but instead the html text is printed in my Console pane. How can I view the table in R-Studio?

1 Answers

One option is to create an RMD file (Create a new file from Rstudio with the option File -> New File -> R Markdown...)

enter image description here

and then specify the results = 'asis' in the chunk. Click on Knit -> Knit to HTML

-RMD file content

---
title: "Ztable"
author: "akrun"
date: "01/11/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown



```{r ztable, results = 'asis', echo = FALSE}
suppressPackageStartupMessages(library(moonBook))
x=table(acs$Dx,acs$smoking)
suppressPackageStartupMessages(library(ztable))
suppressPackageStartupMessages(library(magrittr))
options(ztable.type="html")
z=ztable(x) 

print(z,caption="Table 1. Basic Table")


```

-output

enter image description here


Or another option if we don't want to create an RMD file is to create a function similar to the one showed here

view_ztable <- function(x, ...){
  tab <- paste(capture.output(ztable(x, ...)), collapse = '\n')
  tf <- tempfile(fileext = ".html")
  writeLines(tab, tf)
  rstudioapi::viewer(tf)
}
view_ztable(x, format = 'html', table.attr = "class=nofluid")

-output in viewer

enter image description here

Related