```{r, echo = FALSE, message=FALSE}
# library(dplyr)
suppressPackageStartupMessages(library(dplyr))
library(readr)
library(forcats)
```


# One dimensional vectors

<!-- ## Data classes/types -->

<!--     * Character: strings or individual characters, quoted -->
<!--     * Numeric: any real number(s) -->
<!--     * Integer: any integer(s)/whole numbers (1,2,3) -->
<!--     * Double: any number with fractional values (1.2, 4.01, 1.00004) -->
<!--     * Factor: categorical/qualitative variables -->
<!--     * Logical: variables composed of TRUE or FALSE -->
<!--     * Date/POSIXct: represents calendar dates and times -->


## Character and numeric

We have already covered `character` and `numeric` types.

```{r numChar}
class(c("tree", "cloud", "stars_&_sky"))
class(c(1, 4, 7))
```

## Character and numeric

Character predominates if there are mixed classes.

```{r numChar2}
class(c(1, 2, "tree"))
class(c("1", "4", "7"))
```

## Logical

`logical` is a type that only has two possible elements: `TRUE` and `FALSE`

```{r logical1}
x <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
class(x)
```

`logical` elements are NOT in quotes. 

## General Class Information

There is one useful functions associated with practically all R classes: 

`as.CLASS_NAME(x)` **coerces between classes**. It turns `x` into a certain class.

Examples:

- `as.numeric()`
- `as.character()`
- `as.logical()`

## Coercing: seamless transition

Sometimes coercing works great!

```{r logical_coercion3s}
as.character(4)
as.numeric(c("1", "4", "7"))
as.logical(c("TRUE", "FALSE", "FALSE"))
as.logical(0)
```

## Coercing: not-so-seamless

When interpretation is ambiguous, R will return `NA` (an R constant representing "**N**ot **A**vailable" i.e. missing value)

```{r logical_coercions4}
as.numeric(c("1", "4", "7a"))
as.logical(c("TRUE", "FALSE", "UNKNOWN"))
```

## Number Subclasses

There are two major number subclasses or types

1) Double (1.003)
2) Integer (1)

## Number Subclasses

`Double` is equivalent to `numeric`. It is a number that contains <span style="color: red;">fractional values </span>. Can be any amount of places after the decimal.

`Double` stands for [double-precision](https://en.wikipedia.org/wiki/Double-precision_floating-point_format)

For most purposes, the difference between integers and doubles doesn't matter.

## Significant figures and other formats

The `num` function of the `tibble` package can be used to change format. See here for more: https://tibble.tidyverse.org/articles/numbers.html 

## Factors

A `factor` is a special `character` vector where the elements have pre-defined groups or 'levels'. You can think of these as qualitative or categorical variables. Order is often important.

Examples:

- red, orange, yellow, green, blue, purple
- breakfast, lunch, dinner
- baby, toddler, child, teen, adult
- Strongly Agree, Agree, Neutral, Disagree, Strongly Disagree
- beginner, novice, intermediate, expert

** We will learn more about factors in a later module. **

## Classes Overview

| Example 	| Class 	| Type 	| Notes 	|
|:---:|:---:|:---:|---|
| 1.1 	| Numeric 	| double 	| default for numbers 	|
| 1 	| integer 	| integer 	| Need to coerce to integer with as.integer() or use sample() or seq() with whole numbers	|
| "FALSE", "Ball" 	| Character 	| Character 	| Need quotes 	|
| FALSE, TRUE 	| logical 	| logical 	| No quotes 	|
| "Small", "Large" 	| Factor 	| Factor 	| Need to coerce to factor with factor() 	|

# Special data classes

## Dates

There are two most popular R classes used when working with dates and times: 

- `Date` class representing a calendar date
- `POSIXct` class representing a calendar date with hours, minutes, seconds

We convert data from character to `Date`/`POSIXct` to use functions to manipulate date/date and time

`lubridate` is a powerful, widely used R package from "tidyverse" family to work with `Date` / `POSIXct` class objects 

## Creating `Date` class object  

```{r, message = FALSE}
class("2021-06-15")

library(lubridate)

x <- ymd("2021-06-15") # lubridate package Year Month Day
class(x)
```

Note for function `ymd`: **y**ear **m**onth **d**ay  

## Dates are useful!

```{r}
a <- ymd("2021-06-15")
b <- ymd("2021-06-18")
a - b
```

## The function matches the format

```{r}
mdy("06/15/2021")
dmy("15-June-2021")
ymd("2021-06-15")
```

<!-- Note for  function `mdy`: **m**onth **d**ay  **y**ear -->

<!-- ## They right lubridate function needs to be used -->

<!-- Must match the data format! -->

<!-- ```{r} -->
<!-- ymd("06/15/2021") # This doesn't work - gives NA -->
<!-- mdy("06/15/2021") # This works -->
<!-- ``` -->


<!-- ## Creating `POSIXct` class object   -->

<!-- ```{r} -->
<!-- class("2013-01-24 19:39:07") -->
<!-- ymd_hms("2013-01-24 19:39:07") # lubridate package -->
<!-- class(ymd_hms("2013-01-24 19:39:07")) # lubridate package -->
<!-- ``` -->

<!-- UTC represents time zone, by default: Coordinated Universal Time -->

<!-- Note for  function `ymd_hms`: year month day hour minute second.  -->

<!-- There are functions in case your data have only date, hour and minute (`ymd_hm()`) or only date and hour (`ymd_h()`).  -->


## Class conversion in with a dataset

```{r, results='hide'}
library(dasehr)
covidww <- covid_wastewater %>% select(contains("date"))
```

```{r}
head(covidww)
```

## Class conversion in with a dataset

We would need to use mutate to help us modify that column.

```{r}
covidww %>% 
  mutate(date_start = mdy(date_start))
```

# Other two-dimensional data classes

## Two-dimensional data classes

Two-dimensional classes are those we would often use to store data read from a file 

* a data frame (`data.frame` or `tibble` class)

* a matrix (`matrix` class)

    * also composed of rows and columns
    * unlike `data.frame` or `tibble`, the entire matrix is composed of one R class
    * for example: all entries are `numeric`, or all entries are `character`


## Lists

* One other data type that is the most generic are `lists`.
* Can hold vectors, strings, matrices, models, list of other list!
* Lists are used when you need to do something repeatedly across lots of data - for example wrangling several similar files at once
* Lists are a bit more advanced but you may encounter them when you work with others or look up solutions

## Making Lists

* Can be created using `list()`
```{r makeList}
mylist <- list(c("A", "b", "c"), c(1, 2, 3))
mylist
class(mylist)
```

## Summary

 - two dimensional object classes include: data frames, tibbles, matrices, and lists
 - matrix has columns and rows but  is all one data class
 - lists can contain multiples of any other class of data including lists!
 - calendar dates can be represented with the `Date` class using `ymd()`, `mdy()` functions from `lubridate` package
  - Make sure you choose the right function for the way the date is formatted!
- `POSIXct` class representing a calendar date with hours, minutes, seconds. Can use `ymd_hms()` or `ymd_hm()` or `ymd_h()`functions from the [`lubridate` package](https://lubridate.tidyverse.org/)
- can then easily subtract `Date` or `POSIXct` class variables or pull out aspects like year

## Lab Part 1

🏠 [Class Website](https://daseh.org/) 

💻 [Lab](https://daseh.org/modules//Data_Classes/lab/Data_Classes_Lab.Rmd)

```{r, fig.alt="The End", out.width = "50%", echo = FALSE, fig.align='center'}
knitr::include_graphics(here::here("images/the-end-g23b994289_1280.jpg"))
```

Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=812226">Gerd Altmann</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=812226">Pixabay</a>

# Extra Slides

## Matrices

`as.matrix()` creates a matrix from a data frame or tibble (where all values are the same class).

```{r,}
covidww_mat <- select(covidww, contains("Missouri")) %>%
  head(n = 3)
covidww_mat
as.matrix(covidww_mat)
```

## Matrices

`matrix()` creates a matrix from scratch.

```{r}
matrix(1:6, ncol = 2)
```


## More about Lists

List elements can be named

```{r makeListv}
mylist_named <- list(
  letters = c("A", "b", "c"),
  numbers = c(1, 2, 3),
  one_matrix = matrix(1:4, ncol = 2)
)
mylist_named
```


## Some useful functions from `lubridate` to manipulate `Date` objects

```{r}
x <- ymd(c("2021-06-15", "2021-07-15"))
x
day(x) # see also: month(x) , year(x)
x + days(10)
x + months(1) + days(10)
wday(x, label = TRUE)
```

## Some useful functions from `lubridate` to manipulate `POSIXct` objects

```{r}
x <- ymd_hms("2013-01-24 19:39:07")
x
date(x)
x + hours(3)
floor_date(x, "1 hour") # see also: ceiling_date()
```

## Differences in dates 

```{r}
x1 <- ymd(c("2021-06-15"))
x2 <- ymd(c("2021-07-15"))

difftime(x2, x1, units = "weeks")
as.numeric(difftime(x2, x1, units = "weeks"))
```

Similar can be done with time (e.g. difference in hours). 

# Data Selection

## Matrices

```{r matrix}
n <- 1:9
n
mat <- matrix(n, nrow = 3)
mat
```

## Vectors: data selection

To get element(s) of a vector (one-dimensional object): 

- Type the name of the variable and open the rectangular brackets `[ ]`
- In the rectangular brackets, type index (/vector of indexes) of element (/elements) you want to pull. **In R, indexes start from 1** (not: 0)

```{r}
x <- c("a", "b", "c", "d", "e", "f", "g", "h")
x
x[2]
x[c(1, 2, 100)]
```



## Matrices: data selection

Note you cannot use `dplyr` functions (like `select`) on matrices. To subset matrix rows and/or columns, use `matrix[row_index, column_index]`.

```{r subset3}
mat
mat[1, 1] # individual entry: row 1, column 1
mat[1, 2] # individual entry: row 1, column 2
mat[1, ] # first row
mat[, 1] # first column

mat[c(1, 2), c(2, 3)] # subset of original matrix: two rows and two columns
```


## Lists: data selection

You can reference data from list using `$` (if elements are named) or using `[[ ]]`

```{r}
mylist_named[[1]]
mylist_named[["letters"]] # works only for a list with elements' names
mylist_named$letters # works only for a list with elements' names
```

