--- title: "Tibbles and Tidy Data" author: "Prof. Eric A. Suess" output: word_document: default pdf_document: default html_notebook: default --- Today we will take a look at tibbles, tribbles, and importing data ```{r message=FALSE} library(tidyverse) ``` ## Traditional data.frame ```{r} my.data <- data.frame( x1 = c(12,34,45), x2 = c("M","F", "F") ) my.data class(my.data) ``` # The new data_frame tibble ```{r} my_data <- data_frame( x1 = c(12,34,45), x2 = c("M","F", "F") ) my_data class(my_data) ``` ```{r} mtcars class(mtcars) mtcars <- as.tibble(mtcars) mtcars ``` ## tribble ```{r} my_data <- tribble( ~x1, ~x2, 12, "M", 34, "F", 45, "F" ) my_data class(my_data) ``` ## Access rows and columns ```{r} my_data # columns my_data[1] my_data[[1]] my_data$x1 my_data$x2 # rows my_data[1,] my_data[2,] my_data[3,] ``` ## Read comma separated value data ```{r} my_data2 <- read_csv( "x1, x2 12, M 34, F 45, F" ) my_data2 ``` ## Parsing ```{r} x <- c("TRUE", "FALSE", "FALSE") str(x) class(x) x <- parse_logical(x) str(x) class(x) ``` ```{r} x <- c(23,34,45) str(x) class(x) x <- parse_integer(x) str(x) class(x) ``` ```{r} x <- c("2018-10-06", "2018-10-07", "2018-10-08") str(x) class(x) x <- parse_date(x) str(x) class(x) ``` ```{r} problems(x) ``` ```{r} x <- parse_number(x) str(x) class(x) x <- parse_double(x) str(x) class(x) ``` ## Strings, ASCII code ```{r} charToRaw("Prof. Suess") ``` ## Dates ```{r} parse_date("2018-10-08") ``` ```{r} library(hms) parse_time("06:30 pm") ``` ```{r} parse_date("10/08/18", "%m/%d/%y") ``` ## Parsing a file This is a useful section to read over. It is about read an external .csv file into R. ```{r} challenge <- read_csv(readr_example("challenge.csv")) problems(challenge) ``` ```{r} challenge <- read_csv( readr_example("challenge.csv"), col_types = cols( x = col_integer(), y = col_character() ) ) ``` ```{r} challenge <- read_csv( readr_example("challenge.csv"), col_types = cols( x = col_double(), y = col_character() ) ) head(challenge) tail(challenge) ``` ```{r} challenge <- read_csv( readr_example("challenge.csv"), col_types = cols( x = col_double(), y = col_date() ) ) head(challenge) tail(challenge) ``` ## Writing a csv Write it, go find it, open it in MS Excel. ```{r} write_csv(challenge, "challenge.csv") ``` ## Write an .rds file. This is an R dataset file. ```{r} write_rds(challenge, "challenge.rds") read_rds("challenge.rds") ```