L05 Tibbles

Data Science 1 with R (STAT 301-1)

Author

YOUR NAME

Load Packages

Code
# Loading package(s)
library(tidyverse)
library(nycflights13)
data("mtcars")
data(flights)
data(mpg)

Exercises

Exercise 1

Please read the vignette for the tibble package.

Code
# Access vignette
vignette("tibble")

Done

Exercise 2

Demonstrate how to manually input the data table below into R using each of these functions:

  • tibble()
  • tribble()
price store ounces
3.99 target 128
3.75 walmart 128
3.00 amazon 128
Code
tibble(
  `price` = c(3.99, 3.75, 3),
  `store` = c("target", "walmart", "amazon"), 
  `ounces` = c(128, 128, 128))
# A tibble: 3 × 3
  price store   ounces
  <dbl> <chr>    <dbl>
1  3.99 target     128
2  3.75 walmart    128
3  3    amazon     128
Code
tribble(
  ~price, ~store, ~ounces, 
  #--|--|----
  3.99, "target", 128,
  3.75, "walmart", 128,
  3, "amazon", 128)
# A tibble: 3 × 3
  price store   ounces
  <dbl> <chr>    <dbl>
1  3.99 target     128
2  3.75 walmart    128
3  3    amazon     128

Exercise 3

How can you tell if an object is a tibble? Consider including an example or two. (Hint: try printing mtcars, which is a regular data frame).

Code
print(mtcars)
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
Code
tibble(mtcars)
# A tibble: 32 × 11
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1  21       6  160    110  3.9   2.62  16.5     0     1     4     4
 2  21       6  160    110  3.9   2.88  17.0     0     1     4     4
 3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1
 4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1
 5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2
 6  18.1     6  225    105  2.76  3.46  20.2     1     0     3     1
 7  14.3     8  360    245  3.21  3.57  15.8     0     0     3     4
 8  24.4     4  147.    62  3.69  3.19  20       1     0     4     2
 9  22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2
10  19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4
# … with 22 more rows

Solution

Tibbles will only show the first ten rows, so when we initially print the mtcars dataset, we can see that there are too many rows for it to be a tibble. The icon is another tell, and tibbles will also print a “# A tibble: rows x columns” message before the table.

Exercise 4

Turn mtcars into a tibble and ask R to print only the first 4 observations/rows. Consider using a slice_*() function.

Code
tibble(mtcars) %>%
slice_head(n = 4)
# A tibble: 4 × 11
    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  21       6   160   110  3.9   2.62  16.5     0     1     4     4
2  21       6   160   110  3.9   2.88  17.0     0     1     4     4
3  22.8     4   108    93  3.85  2.32  18.6     1     1     4     1
4  21.4     6   258   110  3.08  3.22  19.4     1     0     3     1

Exercise 5

Run the following operations on df as a data frame. Then turn df into a tibble and run the operations again. What changes? Why might the default data frame behaviors cause problems or frustration?

Code
df <- data.frame(abc = 1, xyz = "a")
df$x
df[, "xyz"]
df[, c("abc", "xyz")]
Code
df <- data.frame(abc = 1, xyz = "a")
df_tibble <- as_tibble(df)

df$x
[1] "a"
Code
df_tibble$x
NULL
Code
df[, "xyz"]
[1] "a"
Code
df_tibble[, "xyz"]
# A tibble: 1 × 1
  xyz  
  <chr>
1 a    
Code
df[, c("abc", "xyz")]
  abc xyz
1   1   a
Code
df_tibble[, c("abc", "xyz")]
# A tibble: 1 × 2
    abc xyz  
  <dbl> <chr>
1     1 a    

Solution

Data frames will automatically find the “x” by autocompleting the rest of the column name if the column simply starts with x, but, with tibble, we need to write out the full column name. The autocompletion would be very problematic in a larger dataset with multiple variables starting with x. With the next example, the first command only returns a vector, but the tibble returns the selected part of the tibble. Finally, in the final example, when we ask for two columns, it returns a dataframe, where the tibble still shows the selected tibble. The inconsistency with the default dataframe command when subsetting is very troubling, and speaks to the benefits of using tibbles.

Exercise 6

If you have the name of a variable stored as an object, for example var <- "mpg", how can you extract the specified variable from a tibble? Write code to demonstrate.

Code
var <- "mpg"

mtcars_tibble<- as.tibble(mtcars)

mtcars_tibble[, var]
# A tibble: 32 × 1
     mpg
   <dbl>
 1  21  
 2  21  
 3  22.8
 4  21.4
 5  18.7
 6  18.1
 7  14.3
 8  24.4
 9  22.8
10  19.2
# … with 22 more rows
Code
mtcars_tibble[[var]]
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4
Code
mtcars_tibble %>%
  select(var)
# A tibble: 32 × 1
     mpg
   <dbl>
 1  21  
 2  21  
 3  22.8
 4  21.4
 5  18.7
 6  18.1
 7  14.3
 8  24.4
 9  22.8
10  19.2
# … with 22 more rows

Exercise 7

How is subsetting via [[ ]] different from using select() when extracting columns of a tibble? (Hint: Investigate using one of our familiar datasets — flights, diamonds, or mpg.)

Code
flights %>% select(dest)
# A tibble: 336,776 × 1
   dest 
   <chr>
 1 IAH  
 2 IAH  
 3 MIA  
 4 BQN  
 5 ATL  
 6 ORD  
 7 FLL  
 8 IAD  
 9 MCO  
10 ORD  
# … with 336,766 more rows
Code
flights[["dest"]][c(1:7)]
[1] "IAH" "IAH" "MIA" "BQN" "ATL" "ORD" "FLL"

Solution

The select() function returns a tibble, but subsetting via [[ ]] returns a character vector. To limit the amount of rows in the vector, we can add the [c(1:7)], which would allow us to just look at the first seven rows. If not, the qmd file would become way too long to scroll through.

Exercise 8

Practice referring to non-syntactic names in the following data frame by:

Code
# toy dataset
annoying <- tibble(
  `1` = 1:10,
  `2` = `1` * 2 + rnorm(length(`1`))
)
  1. Extracting the variable called 1.
  2. Plotting a scatterplot of 1 vs 2.
  3. Creating a new column called 3 which is 2 divided by 1.
  4. Renaming the columns to one, two and three.
Code
# a
annoying[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10
Code
# b
annoying %>%
ggplot(aes(x= `1`, y = `2`)) + geom_point()

Code
#c
updated <- annoying %>%
  add_column(`3` = (.$`2`/.$`1`))

#d
updated %>%
  rename(one = `1`, two = `2`, three = `3`)
# A tibble: 10 × 3
     one   two three
   <int> <dbl> <dbl>
 1     1  1.78  1.78
 2     2  4.18  2.09
 3     3  6.24  2.08
 4     4  7.90  1.98
 5     5 10.1   2.02
 6     6 10.5   1.75
 7     7 14.9   2.13
 8     8 17.8   2.22
 9     9 17.9   1.99
10    10 20.6   2.06

Exercise 9

What does tibble::enframe() do? When might you use it? (Hint: A named vector is one where each value has a specified name – examples in code below.)

Code
# example of a named vector
named_vector <- c("I" = 3.14, "love" = 2.72, "stats!" = 1.61)

# Consider how enframe() would be helpful in the following example:

# random sample of 1000 from a normal distribution
foo <- rnorm(n = 1000, mean = 100, sd = 15)
summary(foo)
Code
foo <- rnorm(n = 1000, mean = 100, sd = 15)
summary(foo)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  54.87   89.85   99.82  100.02  110.51  154.24 
Code
tibble::enframe(foo)
# A tibble: 1,000 × 2
    name value
   <int> <dbl>
 1     1 102. 
 2     2 108. 
 3     3  89.6
 4     4 109. 
 5     5 134. 
 6     6 107. 
 7     7  87.8
 8     8  98.7
 9     9  86.7
10    10  84.6
# … with 990 more rows

Solution

tibble:enframe() converts named vectors to one-to-two column data frames. You would use this to take a list/named vector to a readible vertical column.

Exercise 10

Apply tibble::glimpse() to the flights dataset. Then apply print() to flights. When/why might glimpse() be more useful than print()?

Code
tibble::glimpse(flights)
Rows: 336,776
Columns: 19
$ year           <int> 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2…
$ month          <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
$ day            <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
$ dep_time       <int> 517, 533, 542, 544, 554, 554, 555, 557, 557, 558, 558, …
$ sched_dep_time <int> 515, 529, 540, 545, 600, 558, 600, 600, 600, 600, 600, …
$ dep_delay      <dbl> 2, 4, 2, -1, -6, -4, -5, -3, -3, -2, -2, -2, -2, -2, -1…
$ arr_time       <int> 830, 850, 923, 1004, 812, 740, 913, 709, 838, 753, 849,…
$ sched_arr_time <int> 819, 830, 850, 1022, 837, 728, 854, 723, 846, 745, 851,…
$ arr_delay      <dbl> 11, 20, 33, -18, -25, 12, 19, -14, -8, 8, -2, -3, 7, -1…
$ carrier        <chr> "UA", "UA", "AA", "B6", "DL", "UA", "B6", "EV", "B6", "…
$ flight         <int> 1545, 1714, 1141, 725, 461, 1696, 507, 5708, 79, 301, 4…
$ tailnum        <chr> "N14228", "N24211", "N619AA", "N804JB", "N668DN", "N394…
$ origin         <chr> "EWR", "LGA", "JFK", "JFK", "LGA", "EWR", "EWR", "LGA",…
$ dest           <chr> "IAH", "IAH", "MIA", "BQN", "ATL", "ORD", "FLL", "IAD",…
$ air_time       <dbl> 227, 227, 160, 183, 116, 150, 158, 53, 140, 138, 149, 1…
$ distance       <dbl> 1400, 1416, 1089, 1576, 762, 719, 1065, 229, 944, 733, …
$ hour           <dbl> 5, 5, 5, 5, 6, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6…
$ minute         <dbl> 15, 29, 40, 45, 0, 58, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 0…
$ time_hour      <dttm> 2013-01-01 05:00:00, 2013-01-01 05:00:00, 2013-01-01 0…
Code
print(flights)
# A tibble: 336,776 × 19
    year month   day dep_time sched_de…¹ dep_d…² arr_t…³ sched…⁴ arr_d…⁵ carrier
   <int> <int> <int>    <int>      <int>   <dbl>   <int>   <int>   <dbl> <chr>  
 1  2013     1     1      517        515       2     830     819      11 UA     
 2  2013     1     1      533        529       4     850     830      20 UA     
 3  2013     1     1      542        540       2     923     850      33 AA     
 4  2013     1     1      544        545      -1    1004    1022     -18 B6     
 5  2013     1     1      554        600      -6     812     837     -25 DL     
 6  2013     1     1      554        558      -4     740     728      12 UA     
 7  2013     1     1      555        600      -5     913     854      19 B6     
 8  2013     1     1      557        600      -3     709     723     -14 EV     
 9  2013     1     1      557        600      -3     838     846      -8 B6     
10  2013     1     1      558        600      -2     753     745       8 AA     
# … with 336,766 more rows, 9 more variables: flight <int>, tailnum <chr>,
#   origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
#   minute <dbl>, time_hour <dttm>, and abbreviated variable names
#   ¹​sched_dep_time, ²​dep_delay, ³​arr_time, ⁴​sched_arr_time, ⁵​arr_delay

Solution

There are 19 different variables to represent as columns, but simply printing the table will cut off the last nine and limit it to ten columns. With glimpse(), however, all 19 variables are present