r4ds/vectors.qmd

660 lines
21 KiB
Plaintext
Raw Normal View History

# Vectors {#sec-vectors}
```{r}
#| results: "asis"
#| echo: false
source("_common.R")
```
2015-12-06 22:02:29 +08:00
2016-07-19 21:01:50 +08:00
## Introduction
2016-04-18 21:45:27 +08:00
2022-09-24 22:26:16 +08:00
So far we've talked about individual data types individual like numbers, strings, factors, tibbles and more.
Now it's time to learn more about how they fit together into a holistic structure.
In this chapter we'll explore the **vector** data type, the type that underlies pretty much all objects that we use to store data in R.
2016-04-18 21:45:27 +08:00
2016-07-19 21:01:50 +08:00
### Prerequisites
The focus of this chapter is on base R data structures, so it isn't essential to load any packages.
We will, however, use a handful of functions from the **purrr** package to avoid some inconsistencies in base R.
2016-08-13 04:22:15 +08:00
```{r}
#| label: setup
#| message: false
2016-10-04 01:30:24 +08:00
library(tidyverse)
2016-08-13 04:22:15 +08:00
```
2016-07-19 21:01:50 +08:00
2016-08-19 05:12:42 +08:00
## Vector basics
2015-12-06 22:02:29 +08:00
2022-09-24 22:26:16 +08:00
There are two fundamental types of vectors:
2016-04-04 22:06:04 +08:00
1. **Atomic** vectors, of which there are six types: **logical**, **integer**, **double**, **character**, **complex**, and **raw**.
Integer and double vectors are collectively known as **numeric** vectors.
2016-04-04 22:06:04 +08:00
2. **Lists**, which are sometimes called recursive vectors because lists can contain other lists.
2016-04-07 22:21:39 +08:00
2022-09-24 22:26:16 +08:00
The chief difference between atomic vectors and lists is that atomic vectors are **homogeneous** (every element is the same type), while lists can be **heterogeneous** (every element can be a different type).
There's one other related object: `NULL`.
`NULL` is often used to represent the absence of a vector (as opposed to `NA` which is used to represent the absence of a value in a vector).
`NULL` typically behaves like a vector of length 0.
2022-09-24 22:26:16 +08:00
@fig-datatypes summarizes the interrelationships.
```{r}
#| label: fig-datatypes
#| echo: false
2022-09-24 22:26:16 +08:00
#| out-width: ~
#| fig-cap: >
#| The hierarchy of R's vector types.
2022-09-24 22:26:16 +08:00
#| fig-alt: >
#| A diagram that uses nested sets to show how R's vector types
#| are related. There are two types at the top level: vectors and
#| NULL. Inside vectors there are two types: atomic and list.
#| Inside atomic there are three types: logical, numeric, and
#| character. Inside numeric there are two types: integer, and
#| double.
2015-12-06 22:02:29 +08:00
2022-09-24 22:26:16 +08:00
knitr::include_graphics("diagrams/data-structures.png", dpi = 270)
2016-03-28 21:23:46 +08:00
```
Every vector has two key properties:
2016-03-28 21:23:46 +08:00
2022-09-24 22:26:16 +08:00
1. Its **type**, which is one of logical, integer, double, character or list.
You can determine this with `typeof()`.
2016-04-04 22:06:04 +08:00
```{r}
typeof(letters)
typeof(1:10)
2022-09-24 22:26:16 +08:00
typeof(2.5)
2016-04-04 22:06:04 +08:00
```
2016-03-11 23:10:20 +08:00
2022-09-24 22:26:16 +08:00
Sometimes you want to do different things based on the type of vector.
One option is to use `typeof()`.
Another is to use a test function which returns a `TRUE` or `FALSE`.
Base R provides many functions like `is.vector()` and `is.atomic()`, but they often return surprising results.
Instead, it's safer to use the `is_*` functions provided by purrr, which correspond exactly to @fig-datatypes.
2. Its **length**, which you can determine with `length()`.
2016-03-11 23:10:20 +08:00
2016-04-04 22:06:04 +08:00
```{r}
x <- list("a", "b", 1:10)
length(x)
```
2016-03-11 23:10:20 +08:00
Vectors can also contain arbitrary additional metadata in the form of attributes.
2022-09-24 22:26:16 +08:00
These attributes are used to create **S3 vectors** which build on additional behavior.
You've seen three S3 vectors in this book:
2016-04-04 22:06:04 +08:00
2022-09-24 22:26:16 +08:00
- Factors (`factor`) are built on top of integer vectors.
- Dates (`date`) are built on top of double vectors.
- Date-times (`POSIXct`) are built on top of double vectors.
You can use S3 to build on top of lists to make things that are fundamentally not vectors, like data frames or linear models.
### Exercises
2016-04-04 22:06:04 +08:00
2022-09-24 22:26:16 +08:00
1. Carefully read the documentation of `is.vector()`. What does it actually test for? Why does `is.atomic()` not agree with the definition of atomic vectors above?
2016-03-11 23:10:20 +08:00
2022-09-24 22:26:16 +08:00
## Atomic vectors
2016-03-11 23:10:20 +08:00
The four most important types of atomic vector are logical, integer, double, and character.
2022-08-10 00:43:12 +08:00
Raw and complex are rarely used during a data analysis, so we won't discuss them here.
2022-09-24 22:26:16 +08:00
The difference between integer and double is rarely important for data science, so we lump them together into numeric.
2016-03-28 21:23:46 +08:00
2016-04-07 22:21:39 +08:00
### Logical
Logical vectors are the simplest type of atomic vector because they can take only three possible values: `FALSE`, `TRUE`, and `NA`.
2022-09-24 22:26:16 +08:00
Logical vectors are usually constructed with comparison operators, as described in @sec-logicals.
2016-04-06 22:02:11 +08:00
2016-03-11 23:10:20 +08:00
### Numeric
2022-09-24 22:26:16 +08:00
Integer and double vectors are known collectively as numeric vectors and were the topic of @sec-numbers.
In R, numbers are doubles by default.
To make an integer, place an `L` after the number:
```{r}
2016-03-11 23:10:20 +08:00
typeof(1)
typeof(1L)
```
2022-09-24 22:26:16 +08:00
The distinction between integers and doubles is not usually important in R, but there are two important differences that you should be aware of:
2016-03-11 23:10:20 +08:00
2022-09-24 22:26:16 +08:00
1. Doubles are approximations, as we discussed in @sec-fp-comparison.
Doubles represent floating point numbers that can not always be precisely represented with a fixed amount of memory.
2022-09-24 22:26:16 +08:00
For example, the square of the square root of two is not two:
2016-03-11 23:10:20 +08:00
2016-08-19 05:12:42 +08:00
```{r}
x <- sqrt(2) ^ 2
x
x - 2
```
2. Integers have one special value: `NA`, while doubles have four: `NA`, `NaN`, `Inf` and `-Inf`.
All three special values `NaN`, `Inf` and `-Inf` can arise during division:
2016-08-19 05:12:42 +08:00
```{r}
c(-1, 0, 1) / 0
```
Avoid using `==` to check for these other special values.
2022-09-24 22:26:16 +08:00
Instead use the helper functions `is.finite()`, `is.infinite()`, and `is.nan()`.
2016-03-11 23:10:20 +08:00
### Character
Character vectors are the most complex type of atomic vector, because each element of a character vector is a string, and a string can contain an arbitrary amount of data.
2022-09-24 22:26:16 +08:00
You already learned many practical tools for working with character vectors in @sec-strings.
2022-08-10 00:43:12 +08:00
Here we wanted to mention one important feature of the underlying string implementation: R uses a global string pool.
This means that each unique string is only stored in memory once, and every use of the string points to that representation.
This reduces the amount of memory needed by duplicated strings.
2022-09-24 22:26:16 +08:00
You can see this behavior in practice with `lobstr::obj_size()`:
2016-03-16 21:01:03 +08:00
```{r}
x <- "This is a reasonably long string."
2022-03-18 04:11:47 +08:00
lobstr::obj_size(x)
2016-03-16 21:01:03 +08:00
2016-07-19 21:01:50 +08:00
y <- rep(x, 1000)
2022-03-18 04:11:47 +08:00
lobstr::obj_size(y)
2016-03-16 21:01:03 +08:00
```
`y` doesn't take up 1,000x as much memory as `x`, because each element of `y` is just a pointer to that same string.
2022-03-18 04:11:47 +08:00
A pointer is 8 bytes, so 1000 pointers to a 152 B string is 8 \* 1000 + 152 = 8,144 B.
2016-03-16 21:01:03 +08:00
### Missing values {#sec-missing-values-vectors}
2016-08-13 04:22:15 +08:00
2016-08-19 05:12:42 +08:00
Note that each type of atomic vector has its own missing value:
2016-08-13 04:22:15 +08:00
```{r}
NA # logical
NA_integer_ # integer
NA_real_ # double
NA_character_ # character
```
2022-09-24 22:26:16 +08:00
This is usually unimportant because `NA` will almost always be automatically converted to the correct type.
2016-04-06 22:02:11 +08:00
### Coercion
2016-04-07 22:21:39 +08:00
There are two ways to convert, or coerce, one type of vector to another:
2016-04-06 22:02:11 +08:00
1. Explicit coercion happens when you call a function like `as.logical()`, `as.integer()`, `as.double()`, or `as.character()`.
Whenever you find yourself using explicit coercion, you should always check whether you can make the fix upstream, so that the vector never had the wrong type in the first place.
For example, you may need to tweak your readr `col_types` specification.
2016-04-18 21:45:27 +08:00
2. Implicit coercion happens when you use a vector in a specific context that expects a certain type of vector.
For example, when you use a logical vector with a numeric summary function, or when you use a double vector where an integer vector is expected.
2016-04-18 21:45:27 +08:00
2022-08-10 00:43:12 +08:00
Because explicit coercion is used relatively rarely, and is largely easy to understand, we'll focus on implicit coercion here.
You've already seen the most important type of implicit coercion: using a logical vector in a numeric context.
In this case `TRUE` is converted to `1` and `FALSE` converted to `0`.
That means the sum of a logical vector is the number of trues, and the mean of a logical vector is the proportion of trues:
2016-04-06 22:02:11 +08:00
```{r}
2016-04-07 22:21:39 +08:00
x <- sample(20, 100, replace = TRUE)
y <- x > 10
sum(y) # how many are greater than 10?
mean(y) # what proportion are greater than 10?
2016-04-06 22:02:11 +08:00
```
2016-04-18 21:45:27 +08:00
It's also important to understand what happens when you try and create a vector containing multiple types with `c()`: the most complex type always wins.
2016-04-06 22:02:11 +08:00
```{r}
2016-08-13 04:22:15 +08:00
typeof(c(TRUE, 1L))
typeof(c(1L, 1.5))
typeof(c(1.5, "a"))
2016-04-06 22:02:11 +08:00
```
An atomic vector can not have a mix of different types because the type is a property of the complete vector, not the individual elements.
2022-09-24 22:26:16 +08:00
If you need to mix multiple types in the same vector, you should use a list.
2016-04-18 21:45:27 +08:00
2022-09-24 22:26:16 +08:00
### Exercises
2016-04-06 22:02:11 +08:00
2022-09-24 22:26:16 +08:00
1. Describe the difference between `is.finite(x)` and `!is.infinite(x)`.
2016-04-06 22:02:11 +08:00
2022-09-24 22:26:16 +08:00
2. Read the source code for `dplyr::near()` (Hint: to see the source code, drop the `()`).
How does it work?
2016-04-06 22:02:11 +08:00
2022-09-24 22:26:16 +08:00
3. A logical vector can take 3 possible values.
How many possible values can an integer vector take?
How many possible values can a double take?
Use Google to do some research.
2016-04-18 21:45:27 +08:00
2022-09-24 22:26:16 +08:00
4. Brainstorm at least four functions that allow you to convert a double to an integer.
How do they differ?
Be precise.
5. What functions from the readr package allow you to turn a string into logical, integer, and double vector?
2016-04-18 21:45:27 +08:00
2022-09-24 22:26:16 +08:00
6. Compare and contrast `setNames()` with `purrr::set_names()`.
## Lists {#sec-lists}
Lists are a step up in complexity from atomic vectors, because lists can contain other lists.
This makes them suitable for representing hierarchical or tree-like structures, as you saw in @sec-rectangling.
You create a list with `list()`:
2016-04-18 21:45:27 +08:00
```{r}
2022-09-24 22:26:16 +08:00
x <- list(1, 2, 3)
x
2016-04-18 21:45:27 +08:00
```
2022-09-24 22:26:16 +08:00
A very useful tool for working with lists is `str()` because it focuses on the **str**ucture, not the contents.
2016-04-18 21:45:27 +08:00
2022-09-24 22:26:16 +08:00
```{r}
str(x)
x_named <- list(a = 1, b = 2, c = 3)
str(x_named)
```
Unlike atomic vectors, `list()` can contain a mix of objects:
2016-04-18 21:45:27 +08:00
```{r}
2022-09-24 22:26:16 +08:00
y <- list("a", 1L, 1.5, TRUE)
str(y)
2016-04-18 21:45:27 +08:00
```
2022-09-24 22:26:16 +08:00
Lists can even contain other lists!
2016-04-18 21:45:27 +08:00
```{r}
2022-09-24 22:26:16 +08:00
z <- list(list(1, 2), list(3, 4))
str(z)
2016-04-18 21:45:27 +08:00
```
2022-09-24 22:26:16 +08:00
To explain more complicated list manipulation functions, it's helpful to have a visual representation of lists.
For example, take these three lists:
2016-04-18 21:45:27 +08:00
```{r}
2022-09-24 22:26:16 +08:00
x1 <- list(c(1, 2), c(3, 4))
x2 <- list(list(1, 2), list(3, 4))
x3 <- list(1, list(2, list(3)))
```
2022-09-24 22:26:16 +08:00
We'll draw them as follows:
2016-08-19 05:12:42 +08:00
2022-09-24 22:26:16 +08:00
```{r}
#| echo: false
#| out-width: "75%"
2016-08-19 05:12:42 +08:00
2022-09-24 22:26:16 +08:00
knitr::include_graphics("diagrams/lists-structure.png")
2016-04-18 21:45:27 +08:00
```
2022-09-24 22:26:16 +08:00
There are three principles:
1. Lists have rounded corners.
Atomic vectors have square corners.
2. Children are drawn inside their parent, and have a slightly darker background to make it easier to see the hierarchy.
3. The orientation of the children (i.e. rows or columns) isn't important, so we'll pick a row or column orientation to either save space or illustrate an important property in the example.
### Names
2016-04-06 22:02:11 +08:00
All types of vectors can be named.
2022-09-24 22:26:16 +08:00
But names they seem particularly useful for lists.
You can name them during creation with `list()`:
2016-04-06 22:02:11 +08:00
```{r}
2022-09-24 22:26:16 +08:00
list(x = 1, y = 2, z = 4)
2016-04-06 22:02:11 +08:00
```
2016-04-07 22:21:39 +08:00
Or after the fact with `purrr::set_names()`:
2016-04-06 22:02:11 +08:00
2016-04-07 22:21:39 +08:00
```{r}
2022-09-24 22:26:16 +08:00
set_names(list(1, 2, 3), c("a", "b", "c"))
2016-04-07 22:21:39 +08:00
```
Named vectors are most useful for subsetting, described next.
2016-04-06 22:02:11 +08:00
2022-09-24 22:26:16 +08:00
### Exercises
1. Draw the following lists as nested sets:
a. `list(a, b, list(c, d), list(e, f))`
b. `list(list(list(list(list(list(a))))))`
## Subsetting {#sec-vector-subsetting}
There are three subsetting tools in base R: `[`, `[[`, and `$`.
We'll see how they apply to atomic vectors and lists.
And then how they combine to provide an alternative to `filter()` and `select()` for working with data frames.
### Atomic vectors
2016-04-06 22:02:11 +08:00
`[` is the subsetting function, and is called like `x[a]`.
There are four types of things that you can subset a vector with:
1. A numeric vector containing only integers.
The integers must either be all positive, all negative, or zero.
2016-04-06 22:02:11 +08:00
2016-04-18 21:45:27 +08:00
Subsetting with positive integers keeps the elements at those positions:
2016-04-06 22:02:11 +08:00
```{r}
x <- c("one", "two", "three", "four", "five")
x[c(3, 2, 5)]
```
By repeating a position, you can actually make a longer output than input:
2016-04-06 22:02:11 +08:00
```{r}
x[c(1, 1, 5, 5, 5, 2)]
```
2016-04-06 22:02:11 +08:00
Negative values drop the elements at the specified positions:
2016-04-06 22:02:11 +08:00
```{r}
x[c(-1, -3, -5)]
```
2016-04-18 21:45:27 +08:00
It's an error to mix positive and negative values:
```{r}
#| error: true
2016-04-06 22:02:11 +08:00
x[c(1, -1)]
```
The error message mentions subsetting with zero, which returns no values:
2016-04-06 22:02:11 +08:00
```{r}
x[0]
```
This is not useful very often, but it can be helpful if you want to create unusual data structures to test your functions with.
2. Subsetting with a logical vector keeps all values corresponding to a `TRUE` value.
This is most often useful in conjunction with the comparison functions.
2016-08-13 04:22:15 +08:00
```{r}
x <- c(10, 3, NA, 5, 8, 1, NA)
2016-04-06 22:02:11 +08:00
# All non-missing values of x
x[!is.na(x)]
2016-08-13 04:22:15 +08:00
# All even (or missing!) values of x
2016-04-06 22:02:11 +08:00
x[x %% 2 == 0]
```
3. If you have a named vector, you can subset it with a character vector:
2016-04-06 22:02:11 +08:00
```{r}
x <- c(abc = 1, def = 2, xyz = 5)
x[c("xyz", "def")]
```
Like with positive integers, you can also use a character vector to duplicate individual entries.
4. The simplest type of subsetting is nothing, `x[]`, which returns the complete `x`.
This is not useful for subsetting vectors, but it is useful when subsetting matrices (and other high dimensional structures) because it lets you select all the rows or all the columns, by leaving that index blank.
For example, if `x` is 2d, `x[1, ]` selects the first row and all the columns, and `x[, -1]` selects all rows and all columns except the first.
To learn more about the applications of subsetting, reading the "Subsetting" chapter of *Advanced R*: <http://adv-r.had.co.nz/Subsetting.html#applications>.
There is an important variation of `[` called `[[`.
`[[` only ever extracts a single element, and always drops names.
It's a good idea to use it whenever you want to make it clear that you're extracting a single item, as in a for loop.
The distinction between `[` and `[[` is most important for lists, as we'll see shortly.
2016-04-06 22:02:11 +08:00
2022-09-24 22:26:16 +08:00
### Lists
2022-08-10 00:43:12 +08:00
There are three ways to subset a list, which we'll illustrate with a list named `a`:
```{r}
a <- list(a = 1:3, b = "a string", c = pi, d = list(-1, -5))
```
- `[` extracts a sub-list.
The result will always be a list.
```{r}
str(a[1:2])
str(a[4])
```
Like with vectors, you can subset with a logical, integer, or character vector.
- `[[` extracts a single component from a list.
It removes a level of hierarchy from the list.
```{r}
2016-10-26 21:29:32 +08:00
str(a[[1]])
str(a[[4]])
```
- `$` is a shorthand for extracting named elements of a list.
It works similarly to `[[` except that you don't need to use quotes.
```{r}
a$a
2016-08-13 04:22:15 +08:00
a[["a"]]
```
The distinction between `[` and `[[` is really important for lists, because `[[` drills down into the list while `[` returns a new, smaller list.
Compare the code and output above with the visual representation in @fig-lists-subsetting.
```{r}
#| label: fig-lists-subsetting
#| echo: false
#| out-width: "75%"
#| fig-cap: >
#| Subsetting a list, visually.
knitr::include_graphics("diagrams/lists-subsetting.png")
```
The difference between `[` and `[[` is very important, but it's easy to get confused.
2022-09-24 22:26:16 +08:00
To help you remember, let me show you an unusual pepper shaker in @fig-pepper-1.If this pepper shaker is your list `pepper`, then, `pepper[1]` is a pepper shaker containing a single pepper packet, as in @fig-pepper-2. `pepper[2]` would look the same, but would contain the second packet.
`pepper[1:2]` would be a pepper shaker containing two pepper packets.
`pepper[[1]]` would extract the pepper packet itself, as in @fig-pepper-3.
```{r}
2022-09-24 22:26:16 +08:00
#| label: fig-pepper-1
#| echo: false
#| out-width: "25%"
2022-09-24 22:26:16 +08:00
#| fig-cap: A pepper shaker that Hadley once found in his hotel room.
#| fig-alt: >
#| A photo of a glass pepper shaker. Instead of the pepper shaker
#| containing pepper, it contains many packets of pepper.
knitr::include_graphics("images/pepper.jpg")
```
```{r}
2022-09-24 22:26:16 +08:00
#| label: fig-pepper-2
#| echo: false
#| out-width: "25%"
2022-09-24 22:26:16 +08:00
#| fig-cap: >
#| `pepper[1]`
#| fig-alt: >
#| A photo of the glass pepper shaker containing just one packet of
#| pepper.
knitr::include_graphics("images/pepper-1.jpg")
```
```{r}
2022-09-24 22:26:16 +08:00
#| label: fig-pepper-3
#| echo: false
#| out-width: "25%"
2022-09-24 22:26:16 +08:00
#| fig-cap: >
#| `pepper[[1]]`
#| fig-alt: A single packet of pepper.
knitr::include_graphics("images/pepper-2.jpg")
```
2022-09-24 22:26:16 +08:00
### Data frames
2022-09-24 22:26:16 +08:00
1d subsetting behaves like a list.
2d behaves like a combination of subsetting rows and columns.
### Exercises
2022-09-24 22:26:16 +08:00
4. Create functions that take a vector as input and return:
2022-09-24 22:26:16 +08:00
a. The last value. Should you use `[` or `[[`?
b. The elements at even numbered positions.
c. Every element except the last value.
d. Only even numbers (and no missing values).
5. Why is `x[-which(x > 0)]` not the same as `x[x <= 0]`?
2022-09-24 22:26:16 +08:00
6. What happens when you subset with a positive integer that's bigger than the length of the vector?
What happens when you subset with a name that doesn't exist?
7. What happens if you subset a tibble as if you're subsetting a list?
2016-08-19 05:12:42 +08:00
What are the key differences between a list and a tibble?
2022-09-24 22:26:16 +08:00
## Attributes and S3 vectors
2016-04-18 21:45:27 +08:00
Any vector can contain arbitrary additional metadata through its **attributes**.
You can think of attributes as named list of vectors that can be attached to any object.
2016-08-19 05:12:42 +08:00
You can get and set individual attribute values with `attr()` or see them all at once with `attributes()`.
2016-03-11 23:10:20 +08:00
2016-03-14 22:11:24 +08:00
```{r}
2016-03-28 21:23:46 +08:00
x <- 1:10
attr(x, "greeting")
attr(x, "greeting") <- "Hi!"
attr(x, "farewell") <- "Bye!"
attributes(x)
2016-03-14 22:11:24 +08:00
```
2016-03-28 21:23:46 +08:00
There are three very important attributes that are used to implement fundamental parts of R:
2016-03-16 21:01:03 +08:00
1. **Names** are used to name the elements of a vector.
2. **Dimensions** (dims, for short) make a vector behave like a matrix or array.
3. **Class** is used to implement the S3 object oriented system.
2016-03-28 21:23:46 +08:00
You've seen names above, and we won't cover dimensions because we don't use matrices in this book.
2022-09-24 22:26:16 +08:00
### Class
It remains to describe the class, which controls how **generic functions** work.
Generic functions are key to object oriented programming in R, because they make functions behave differently for different classes of input.
A detailed discussion of object oriented programming is beyond the scope of this book, but you can read more about it in *Advanced R* at <http://adv-r.had.co.nz/OO-essentials.html#s3>.
2016-04-18 21:45:27 +08:00
Here's what a typical generic function looks like:
2016-03-14 22:11:24 +08:00
```{r}
2016-03-28 21:23:46 +08:00
as.Date
2016-03-16 21:01:03 +08:00
```
The call to "UseMethod" means that this is a generic function, and it will call a specific **method**, a function, based on the class of the first argument.
(All methods are functions; not all functions are methods).
You can list all the methods for a generic with `methods()`:
2016-03-28 21:23:46 +08:00
```{r}
methods("as.Date")
```
2016-03-16 21:01:03 +08:00
2016-10-19 21:50:39 +08:00
For example, if `x` is a character vector, `as.Date()` will call `as.Date.character()`; if it's a factor, it'll call `as.Date.factor()`.
2016-08-13 04:22:15 +08:00
You can see the specific implementation of a method with `getS3method()`:
2016-03-16 21:01:03 +08:00
2016-03-28 21:23:46 +08:00
```{r}
getS3method("as.Date", "default")
getS3method("as.Date", "numeric")
2016-03-14 22:11:24 +08:00
```
The most important S3 generic is `print()`: it controls how the object is printed when you type its name at the console.
Other important generics are the subsetting functions `[`, `[[`, and `$`.
2016-08-13 04:22:15 +08:00
2016-03-28 21:23:46 +08:00
### Factors
2016-03-16 21:01:03 +08:00
Factors are designed to represent categorical data that can take a fixed set of possible values.
Factors are built on top of integers, and have a levels attribute:
2016-03-16 21:01:03 +08:00
2016-03-28 21:23:46 +08:00
```{r}
x <- factor(c("ab", "cd", "ab"), levels = c("ab", "cd", "ef"))
typeof(x)
attributes(x)
```
2016-07-27 05:01:19 +08:00
### Dates and date-times
2016-03-28 21:23:46 +08:00
2016-08-19 05:12:42 +08:00
Dates in R are numeric vectors that represent the number of days since 1 January 1970.
2016-03-28 21:23:46 +08:00
```{r}
x <- as.Date("1971-01-01")
unclass(x)
typeof(x)
attributes(x)
```
Date-times are numeric vectors with class `POSIXct` that represent the number of seconds since 1 January 1970.
(In case you were wondering, "POSIXct" stands for "Portable Operating System Interface", calendar time.)
2016-03-28 21:23:46 +08:00
```{r}
x <- lubridate::ymd_hm("1970-01-01 01:00")
unclass(x)
typeof(x)
attributes(x)
```
The `tzone` attribute is optional.
It controls how the time is printed, not what absolute time it refers to.
2016-04-18 21:45:27 +08:00
```{r}
attr(x, "tzone") <- "US/Pacific"
x
2016-08-13 04:22:15 +08:00
2016-04-18 21:45:27 +08:00
attr(x, "tzone") <- "US/Eastern"
x
```
2016-03-28 21:23:46 +08:00
There is another type of date-times called POSIXlt.
These are built on top of named lists:
2016-03-28 21:23:46 +08:00
```{r}
y <- as.POSIXlt(x)
typeof(y)
attributes(y)
```
POSIXlts are rare inside the tidyverse.
They do crop up in base R, because they are needed to extract specific components of a date, like the year or month.
Since lubridate provides helpers for you to do this instead, you don't need them.
POSIXct's are always easier to work with, so if you find you have a POSIXlt, you should always convert it to a regular date time with `lubridate::as_datetime()`.
2016-03-28 21:23:46 +08:00
2022-09-24 22:26:16 +08:00
## Other types
2016-08-13 04:22:15 +08:00
### Tibbles
2016-03-28 21:23:46 +08:00
2016-08-13 04:22:15 +08:00
Tibbles are augmented lists: they have class "tbl_df" + "tbl" + "data.frame", and `names` (column) and `row.names` attributes:
2016-03-28 21:23:46 +08:00
```{r}
2016-08-13 04:22:15 +08:00
tb <- tibble::tibble(x = 1:5, y = 5:1)
typeof(tb)
attributes(tb)
2016-03-28 21:23:46 +08:00
```
The difference between a tibble and a list is that all the elements of a data frame must be vectors with the same length.
All functions that work with tibbles enforce this constraint.
2016-03-28 21:23:46 +08:00
Traditional `data.frame`s have a very similar structure:
2016-03-28 21:23:46 +08:00
```{r}
2016-08-13 04:22:15 +08:00
df <- data.frame(x = 1:5, y = 5:1)
typeof(df)
attributes(df)
2016-03-28 21:23:46 +08:00
```
The main difference is the class.
The class of tibble includes "data.frame" which means tibbles inherit the regular data frame behaviour by default.
2016-08-13 04:22:15 +08:00
### Exercises
1. What does `hms::hms(3600)` return?
How does it print?
What primitive type is the augmented vector built on top of?
What attributes does it use?
2. Try and make a tibble that has columns with different lengths.
What happens?
2016-08-19 05:12:42 +08:00
3. Based on the definition above, is it ok to have a list as a column of a tibble?