Today we will take a look at tibbles, tribbles, and importing data

library(tidyverse)

Traditional data.frame

my.data <- data.frame(
  x1 = c(12,34,45),
  x2 = c("M","F", "F")
)
my.data
class(my.data)

The new data_frame tibble

my_data <- data_frame(
  x1 = c(12,34,45),
  x2 = c("M","F", "F")
)
my_data
class(my_data)
mtcars
class(mtcars)

mtcars <- as.tibble(mtcars)
mtcars

tribble

my_data <- tribble(
  ~x1,  ~x2,
  12,   "M",
  34,   "F",
  45,   "F"
)
my_data
class(my_data)

Access rows and columns

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

my_data2 <- read_csv(
  "x1, x2
   12,  M
   34,  F
   45,  F"
)
my_data2

Parsing

x <- c("TRUE", "FALSE", "FALSE")
str(x)
class(x)

x <- parse_logical(x)
str(x)
class(x)
x <- c(23,34,45)
str(x)
class(x)

x <- parse_integer(x)
str(x)
class(x)
x <- c("2018-10-06", "2018-10-07", "2018-10-08")
str(x)
class(x)

x <- parse_date(x)
str(x)
class(x)
problems(x)
x <- parse_number(x)
str(x)
class(x)

x <- parse_double(x)
str(x)
class(x)

Strings, ASCII code

charToRaw("Prof. Suess")

Dates

parse_date("2018-10-08")
library(hms)

parse_time("06:30 pm")
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.

challenge <- read_csv(readr_example("challenge.csv"))

problems(challenge)
challenge <- read_csv(
  readr_example("challenge.csv"), 
  col_types = cols(
    x = col_integer(),
    y = col_character()
  )
)
challenge <- read_csv(
  readr_example("challenge.csv"), 
  col_types = cols(
    x = col_double(),
    y = col_character()
  )
)
head(challenge)
tail(challenge)
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.

write_csv(challenge, "challenge.csv")

Write an .rds file. This is an R dataset file.

write_rds(challenge, "challenge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