---
title: "Working with Your Data in R"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Working with Your Data in R}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

> **Online version.** This guide is also published on ZENTRA Cloud as
> [Working with Your Data in R](https://docs.zentracloud.io/l/en/article/bohtqxbqrm-working-with-your-data-in-r).
> This vignette ships with the package for offline use.

Once `zc_get_readings()` (or `zc_sync()`) has given you a data frame of readings,
here are the everyday R commands for looking at it, filtering it, summarising it,
and saving it. You need very little R to be productive — this covers the
essentials, with links to fuller R guides at the end.

Throughout, `readings` is the tidy data frame returned by `zc_get_readings()`:

```{r}
library(zentraR)
readings <- zc_get_readings("z6-00930", start = Sys.Date() - 7)
```

## Save results so you can reuse them

The single most useful habit in R: **store a result in a named object with `<-`,
or it prints once and is gone.**

```{r}
# Prints once, then lost:
zc_pivot_wider(readings)

# Saved as `wide` — now you can view it, filter it, plot it, or export it:
wide <- zc_pivot_wider(readings)
wide
```

You choose the name (`wide`, `daily`, `air_temp`, ...). The `<-` is R's assignment
arrow: *name on the left, value on the right*.

## Look at your data

```{r}
readings                 # a tibble: prints the first 10 rows and the column types
View(readings)           # open the RStudio spreadsheet viewer (capital V)
head(readings, 20)       # first 20 rows;  tail(readings) for the last few
str(readings)            # structure: every column and its type
dplyr::glimpse(readings) # a tidy, transposed overview
summary(readings)        # quick per-column statistics
dim(readings)            # number of rows and columns;  nrow() / ncol()
names(readings)          # the column names
```

`View()` is interactive (RStudio only) — in a script or a scheduled job use
`print()`, `head()`, or `str()` instead.

## See what's inside

`readings$column` pulls out a single column by name. Combine that with a few base
functions to get your bearings:

```{r}
unique(readings$measurement)   # which measurements are present
table(readings$measurement)    # how many readings of each
unique(readings$device_id)     # which devices
range(readings$datetime)       # earliest and latest timestamp
```

## Filter and sort

The `dplyr` package (part of the tidyverse) reads almost like English:

```{r}
library(dplyr)

# Keep only valid air-temperature readings:
readings |> filter(measurement == "Air Temperature", error_code == 0)

# Highest values first:
readings |> arrange(desc(value))
```

The `|>` is R's pipe: it feeds the value on its left into the function on its
right. Base R does the same with square brackets, if you prefer:

```{r}
readings[readings$measurement == "Air Temperature", ]
```

## Quick summaries

```{r}
mean(readings$value, na.rm = TRUE)   # na.rm = TRUE ignores missing values

# Average and count per measurement:
readings |>
  group_by(measurement) |>
  summarise(avg = mean(value, na.rm = TRUE), n = n())
```

## A quick plot

```{r}
plot(readings$datetime, readings$value, type = "l")
```

For publication-quality graphics with `ggplot2`, see the plotting example in the
*Getting Started with zentraR* vignette.

## Save and export

```{r}
# CSV — opens in Excel / Google Sheets, easy to share:
write.csv(readings, "readings.csv", row.names = FALSE)

# RDS — an exact copy of the R object (types preserved); reload with readRDS():
saveRDS(readings, "readings.rds")
readings <- readRDS("readings.rds")
```

For an automated, incremental local archive, use zentraR's own stores
(`zc_store_csv()`, `zc_store_rds()`) with `zc_sync()` — see the
*Scheduling Automatic Syncs* vignette.

## Getting help

```{r}
?zc_get_readings                 # the help page for any function
vignette(package = "zentraR")    # list this package's guides
```

## Learn more R

These free resources cover R itself, well beyond what you need for zentraR:

- [R for Data Science (2nd ed.)](https://r4ds.hadley.nz/) — the standard
  introduction to the tidyverse.
- [Posit cheatsheets](https://opensource.posit.co/resources/cheatsheets/) — one-page
  references for `dplyr`, `ggplot2`, RStudio, and more.
- [RStudio beginner resources](https://education.rstudio.com/learn/beginner/) —
  guided starting points.

Related zentraR guides:

```{r}
vignette("getting-started", package = "zentraR")
vignette("scheduling", package = "zentraR")
```
