library(tidyverse)
library(openintro)
library(ggplot2)Introduction to Data - Notes
1 - Language of Data
Importing Packages
Using the dataset given by openintro (hsb2)
glimpse(hsb2) # the glimpse method shows the metadata and variables of the data frameRows: 200
Columns: 11
$ id <int> 70, 121, 86, 141, 172, 113, 50, 11, 84, 48, 75, 60, 95, 104, 3…
$ gender <chr> "male", "female", "male", "male", "male", "male", "male", "mal…
$ race <chr> "white", "white", "white", "white", "white", "white", "african…
$ ses <fct> low, middle, high, high, middle, middle, middle, middle, middl…
$ schtyp <fct> public, public, public, public, public, public, public, public…
$ prog <fct> general, vocational, general, vocational, academic, academic, …
$ read <int> 57, 68, 44, 63, 47, 44, 50, 34, 63, 57, 60, 57, 73, 54, 45, 42…
$ write <int> 52, 59, 33, 44, 52, 52, 59, 46, 57, 55, 46, 65, 60, 63, 57, 49…
$ math <int> 41, 53, 54, 47, 57, 51, 42, 45, 54, 52, 51, 51, 71, 57, 50, 43…
$ science <int> 47, 63, 58, 53, 53, 63, 53, 39, 58, 50, 53, 63, 61, 55, 31, 50…
$ socst <int> 57, 61, 31, 56, 61, 61, 61, 36, 51, 51, 61, 61, 71, 46, 56, 56…
We can count the categorical variables (mostly ‘fct’)
hsb2 |>
count(schtyp) # "|>" is the pipe operator - takes result of method call and passes as first argument# A tibble: 2 × 2
schtyp n
<fct> <int>
1 public 168
2 private 32
We can also filter the data to only include observations with certain characteristics
filter(hsb2,schtyp == "public") |>
count(schtyp)# A tibble: 1 × 2
schtyp n
<fct> <int>
1 public 168
Method to find mean of numbers
(avg_reading <- mean(hsb2$read)) # extra parentheses prints out the mean value and assigns it to variable[1] 52.23
Converting numerical variables into categorical ones (Discretization)
hsb2_new <- mutate(hsb2,read_category = if_else(read < avg_reading, "below average", "at or above average"))
count(hsb2_new,read_category)# A tibble: 2 × 2
read_category n
<chr> <int>
1 at or above average 85
2 below average 115
Visualizing Data with ggplot2 (included with tidyverse)
ggplot(data = hsb2, aes(x = science, y = math)) +
geom_point()Color coding the different points:
ggplot(data = hsb2, aes(x = science, y = math,color = prog)) +
geom_point()