---
title: "Printing"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Printing}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

# Basic printing

If a tabulation function is called from the top level, it should print out its table(s) on its own. 

As usual, first, let's start up the package and pick a survey to analyze:

```{r, results='asis'}
library(surveytable)
set_survey(namcs2019sv)
```

Now, when a tabulation function is called from the top level, it prints. You don't need to do anything extra.

```{r, results='asis'}
tab("AGER")
```

If a tabulation function is called not from the top level, such as from within a loop or another function, you do need to call `print()` explicitly for it to print. For example:

```{r, results='asis'}
for (vr in c("AGER", "SEX")) {
  print( tab_subset(vr, "MAJOR", "Preventive care") )
}
```

# Create HTML or PDF tables

Using a Quarto document, you can create tables in many different formats, such as HTML or PDF. Here is a straightforward example of what a Quarto document might look like: 

<!-- https://yihui.org/knitr/faq/ --> 

````{verbatim}
---
title: "My tables"
author: "Me"
format: html
---

# Welcome 

As usual, first, let's start up the package and pick a survey to analyze:

```{r, results='asis'}
library(surveytable)
set_survey(namcs2019sv)
```

# Tables

Take a look at this table:

```{r, results='asis'}
tab("AGER")
```
````

Note the `format` setting, which specifies that this document will create HTML tables. Also note that you do have to add the `results='asis'` argument to the code chunks that print tables. 

# Print using various table-making packages

Use the `output` argument of `set_opts()` to select a table-making package. By default (`output = "auto"`), `surveytable` automatically selects a package depending on whether the output is to the screen (`huxtable`), HTML (`gt`), or PDF (`kableExtra`). You can also explicitly select one of these packages.

Changing the table-making package has a couple of uses:

* It allows you to generate tables in the way that you prefer.
* It allows you to print those tables to a variety of destinations, including the screen, HTML files, or PDF files.

## `huxtable`

```{r}
set_opts(output = "huxtable")
```

This is what printing to the screen looks like.

```r
tab("AGER")
```
```{r, echo=FALSE}
print(tab("AGER"), destination = "")
```

To create HTML tables from an R Markdown notebook or a Quarto document, add the `results='asis'` argument to the code chunk, like so:

````{verbatim}
```{r, results='asis'}
tab("AGER")
```
````

```{r, results='asis', echo=FALSE}
tab("AGER")
```

## `gt`

```{r}
set_opts(output = "gt")
```

With `gt`, printing to the screen and to HTML look the same. Here is what printing to the screen looks like:

```r
tab("AGER")
```
```{r, results='asis', echo=FALSE}
print(tab("AGER"), destination = "")
```

Here is HTML:

````{verbatim}
```{r, results='asis'}
tab("AGER")
```
````

```{r, results='asis', echo=FALSE}
tab("AGER")
```


## `kableExtra`

```{r}
set_opts(output = "kableExtra")
```

We have not implemented screen printing with `kableExtra` yet. Try one of the other packages.

Here is HTML:

````{verbatim}
```{r, results='asis'}
tab("AGER")
```
````

```{r, results='asis', echo=FALSE}
tab("AGER")
```

## `auto`

`auto` is the default option. It automatically selects one of the above packages depending on whether the output is to the screen (`huxtable`), HTML (`gt`), or PDF (`kableExtra`).

```{r}
set_opts(output = "auto")
```

Screen output (this should use `huxtable`):

```r
tab("AGER")
```
```{r, echo=FALSE}
print(tab("AGER"), destination = "")
```

HTML output (this should use `gt`):

````{verbatim}
```{r, results='asis'}
tab("AGER")
```
````

```{r, results='asis', echo=FALSE}
tab("AGER")
```

## Other packages

To use the `flextable` table-making package, type `set_opts(output = "flextable")`.

# Generate unformatted output

Some analysts might wish to compare the output from `surveytable` to the output from other statistical software, such as SAS / SUDAAN. In this situation, `set_opts(raw = TRUE)` might be useful. This command tells `surveytable` to print unformatted and unrounded tables. Please be sure to also specify the `output` argument.

```{r}
set_opts(output = "screen", raw = TRUE)
```

```r
tab("AGER")
```

```{r, echo=FALSE}
print(tab("AGER"), destination = "")
```

```{r}
set_opts(output = "auto", raw = FALSE)
```

Also see `as.data.frame.astra_table()` and `restructure()`.

# Save the tables

## Save tables and charts to an Excel workbook

Before using Excel printing, please be sure to install these packages:

* `openxlsx2` for `output = "Excel"`
* `openxlsx2` and `mschart` for `output = "Excel_v1"`

To save tables and charts to an Excel workbook, turn on Excel printing with `set_opts( output = "Excel", file = "my_workbook" )` or `set_opts( output = "Excel_v1", file = "my_workbook" )`. Set the `file` argument to the name of an Excel file. You **can** specify an existing file, in which case the new tables will be appended to it. 

To save unformatted and unrounded values to an Excel workbook, use `set_opts(output = "Excel", file = "my_workbook", raw = TRUE)` before creating the tables. Raw values are supported with `output = "Excel"`, not `output = "Excel_v1"`.

```r
set_opts(output = "excel", file = "my_workbook")
```

```{r, echo=FALSE}
set_opts(output = "excel", file = "my_workbook", .file_temp = TRUE)
```

Generate some tables:

```{r}
total()
tab("AGER")
```

To turn off Excel printing, set the `output` argument to a value other than `"Excel"`, such as `"auto"`:

```{r}
set_opts(output = "auto")
```

## Save to a CSV file

To save tables to a CSV file, turn on CSV printing with `set_opts( output = "CSV", file = "my_output" )`. Set the `file` argument to the name of a CSV file. You **can** specify an existing file, in which case the new tables will be appended to it. 

To save unformatted and unrounded values to CSV, use `set_opts(output = "CSV", file = "my_output", raw = TRUE)` before creating the tables.

```r
set_opts(output = "csv", file = "my_output")
```

```{r, echo=FALSE}
set_opts(output = "csv", file = "my_output", .file_temp = TRUE)
```

Generate some tables:

```{r}
total()
tab("AGER")
```

To turn off CSV printing, set the `output` argument to a value other than `"CSV"`, such as `"auto"`:

```{r}
set_opts(output = "auto")
```

## Save to a Word document

Before using Word printing, please be sure to install these packages: `flextable` and `officer`. 

To save tables to a Word document, turn on Word printing with `set_opts( output = "Word", file = "my_document" )`. Set the `file` argument to the name of a Word document. You **can** specify an existing file, in which case the new tables will be appended to it. 

```r
set_opts(output = "word", file = "my_document")
```

```{r, echo=FALSE}
set_opts(output = "word", file = "my_document", .file_temp = TRUE)
```

Generate some tables:

```{r}
total()
tab("AGER")
```

To turn off Word printing, set the `output` argument to a value other than `"Word"`, such as `"auto"`:

```{r}
set_opts(output = "auto")
```

## Save to an R data file

Use the built-in `saveRDS()` function to save a table to an R data file:

```r
tab("AGER") |> saveRDS("myfile.rds")
```

You can later load this data file back into R. To print the table, just load the file, like so:

```r
readRDS("myfile.rds")
```

```{r, results='asis', echo=FALSE}
tab("AGER")
```

# Advanced printing

## The proper approach

Advanced users can add functionality to use **any** table-making package that they want. For more information, see `help("surveytable-options")`.

## The "quick-and-dirty" approach

The tabulation functions return either:

* for a single table, which is basically a data frame, with certain attributes set; or
* for more than one table, a list of such tables.

You can convert a single table to a `data.frame` with `as.data.frame()`, like so:

```{r}
tab("AGER") |> as.data.frame()
```

Note that this produces a `data.frame` with unique column names, which improves its usability.

Alternatively, you can pass this `data.frame` to your favorite table-making package. This example passes a table to `gt`. To ensure unique column names, pass the table through `as.data.frame()` first.

```{r}
tab("AGER") |> as.data.frame() |> gt::gt()
```

The reason that this is the "quick-and-dirty" approach is that the output it creates is not as nice as conventional tables, described above. The output does not have table title (which has important information about the variable and the survey), table footer (which has important information about sample size and low-precision estimates), and it does not format the estimates. Nevertheless, there could be situations in which this approach is helpful, such as 

* extracting an exact value from a table using `as.data.frame()`; or 
* quickly using your favorite table-making package.

To restructure tables to make them easier to process programmatically, see `restructure()`. Also see `set_opts(raw = TRUE)`.
