---
title: "Data Classes"
author: "Introduction to R for Public Health Researchers"
output:
  ioslides_presentation:
    css: ../styles.css
    widescreen: yes
---

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

## Data Types:

* One dimensional types ('vectors'):
    * Character: strings or individual characters, quoted
    * Numeric: any real number(s)
    * Integer: any integer(s)/whole numbers
    * Factor: categorical/qualitative variables
    * Logical: variables composed of TRUE or FALSE
    * Date/POSIXct: represents calendar dates and times

## Seq 

- `seq(from, to, by = )` can create sequences
```{r seq}
seq(from = 1, to = 5) 
seq(from = 1, to = 5, by = 0.1) 
```

## Logical

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

```{r logical0}
x = c(TRUE, FALSE, TRUE, TRUE, FALSE)
class(x)
z = c("TRUE", "FALSE", "TRUE", "FALSE")
class(z)
as.logical(z)
```

## `as.` and `is.` functions

- `as.numeric`, `as.character`, `as.logical`, `as.integer` - "coerces"/changes a vector into that data type - MAY RESULT in `NA`
- `is.numeric`, `is.character`, `is.logical`, `is.integer` gives a single `TRUE` or `FALSE` if that vector is that class


```{r logical1}
is.logical(c(TRUE, FALSE))
is.numeric(c(TRUE, FALSE))
as.numeric(c(TRUE, FALSE))
as.numeric(c("5", "0", "$0 "))
as.character(c(TRUE, FALSE))
as.integer(c(TRUE, FALSE))
as.logical(c(5, 0))
```


## 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:

```{r factor1}
x = factor(c("boy", "girl", "girl", "boy", "girl"))
x 
class(x)
```

Note that levels are, by default, in alphanumerical order.


## Factors

- don't use `as.factor`, use `factor`, even when re-creating a factor
- don't use the `relevel` function.  Use the `levels` function to grab the levels if you need.  
- The `fct_relevel` function in `forcats` (in tidyverse) is fine to use.
- Check out the `forcats` functions `fct_inorder`, `fct_infreq`, `fct_lump`


## Dates

- Use the `lubridate` package - period.
- Change dates using `ymd`, `dmy`, or `mdy` or other combinations.
  - `lubridate` cannot guess this - you also don't want it to
  - If some are `ymd` and others are `dmy`, you need to clean
  - `as_date` also is a good function to try
- Make `datetimes` using `ymd_hms`, `ymd_hm`, or `ymd_h`
  - `as_datetime` also is a good function to try

## Lab 

[Lab](http://johnmuschelli.com/intro_to_r/Data_Classes/lab/Data_Classes_Lab.Rmd)

[Website](http://johnmuschelli.com/intro_to_r/index.html)


## Website

[Website](http://johnmuschelli.com/intro_to_r/index.html)

