---
title: "First PX-file"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{First PX-file}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

To create your first PX-file with pxmake, you can either start with an existing PX-file, or use a data set.

## How to create a PX-file from a data set

All workflows in pxmake, starts the same way: by using the `px()` to create a *px object*. Here we are using the built in dataset `population_gl`.

```{r}
library(pxmake)

population_gl |>
  head(10) |>
  print()
```

To create the px object, simply pass the data set to the `px()` function.

```{r}
x <- px(population_gl)
```

`x` is now a px object. The word *object* just means that the PX-file is stored in a specific format that all functions in the pxmake package uses.

Use `px_save()` to save the px object as a PX-file.

```{r}
px_save(x, "population_gl.px")
```

Since we provided no metadata, `px()` added a minimal set of metadata, which is necessary for creating a valid PX-file.

The resulting PX-file can be seen below.

```{r, comment="", echo = FALSE}
readLines('population_gl.px') |> cat(sep = '\n')
```

## How to create a PX-file from a PX-file

If you already have a PX-file, that you want to manipulate using pxmake, simple pass the path of the file, to the `px()` function.

```{r}
x2 <- px("population_gl.px")
```

Just as with the dataset, `x2` is now a px object and can be saved or modified using the other functions in pxmake.


## Modifying a px object

The real fun starts when you start modifying the px object, using one of pxmake many built in functions.

In general, each px keyword has a corresponding function in pxmake. For example, to change the title of the PX-file, you can use the `px_title()` function.

```{r}
x3 <- px_title(x, "Population in Greenland")
```

The `px_title()` function returns a new px object, with the title changed. The original px object is not modified.


```{r}
x3 |>
  px_codepage("UTF-8") |> # Change file encoding  
  px_matrix("pop") |>
  px_contact("Johan Ejstrud") |>
  px_subject_code("GL") |>
  px_subject_area("Greenland") |>
  px_timeval("year") |>
  px_contents("Population in Greenland") |>
  px_units("People") |>
  px_note("See information about data: ?population_gl") |>
  px_last_updated(format(Sys.time(), "%Y%m%d %H:%M")) |>
  px_stub(c("age", "gender")) |> # Change order of STUB variables
  px_save("population_gl_modified.px")
```

The resulting PX-file can be seen below.

```{r, comment="", echo = FALSE}
readLines('population_gl_modified.px') |> cat(sep = '\n')
```

## Advanced use
See the other vignettes for more advanced use cases:
- `vignette("languages")`
- `vignette("micro-files")`
