generated from r4ds/bookclub-template
-
Notifications
You must be signed in to change notification settings - Fork 25
/
03_Vectors.Rmd
2026 lines (1445 loc) · 46.4 KB
/
03_Vectors.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
output: html_document
editor_options:
chunk_output_type: inline
---
# Vectors
**Learning objectives:**
- Learn about different types of vectors and their attributes
- Navigate through vector types and their value types
- Venture into factors and date-time objects
- Discuss the differences between data frames and tibbles
- Do not get absorbed by the `NA` and `NULL` black hole
```{r ch9_setup, message = FALSE, warning = FALSE}
library("dplyr")
library("gt")
library("palmerpenguins")
```
<details>
<summary>Session Info</summary>
```{r}
utils::sessionInfo()
```
</details>
## Aperitif
![Palmer Penguins](images/vectors/lter_penguins.png)
### Counting Penguins
Consider this code to count the number of Gentoo penguins in the `penguins` data set. We see that there are 124 Gentoo penguins.
```{r, eval = FALSE}
sum("Gentoo" == penguins$species)
# output: 124
```
### In
One subtle error can arise in trying out `%in%` here instead.
```{r, results = 'hide'}
species_vector <- penguins |> select(species)
print("Gentoo" %in% species_vector)
# output: FALSE
```
![Where did the penguins go?](images/vectors/lter_penguins_no_gentoo.png)
### Fix: base R
```{r, results = 'hide'}
species_unlist <- penguins |> select(species) |> unlist()
print("Gentoo" %in% species_unlist)
# output: TRUE
```
### Fix: dplyr
```{r, results = 'hide'}
species_pull <- penguins |> select(species) |> pull()
print("Gentoo" %in% species_pull)
# output: TRUE
```
### Motivation
* What are the different types of vectors?
* How does this affect accessing vectors?
<details>
<summary>Side Quest: Looking up the `%in%` operator</summary>
If you want to look up the manual pages for the `%in%` operator with the `?`, use backticks:
```{r, eval = FALSE}
?`%in%`
```
and we find that `%in%` is a wrapper for the `match()` function.
</details>
## Types of Vectors
![Image Credit: Advanced R](images/vectors/summary-tree.png)
Two main types:
- **Atomic**: Elements all the same type.
- **List**: Elements are different Types.
Closely related but not technically a vector:
- **NULL**: Null elements. Often length zero.
## Atomic Vectors
### Types of atomic vectors
![Image Credit: Advanced R](images/vectors/summary-tree-atomic.png)
- **Logical**: True/False
- **Integer**: Numeric (discrete, no decimals)
- **Double**: Numeric (continuous, decimals)
- **Character**: String
### Vectors of Length One
**Scalars** are vectors that consist of a single value.
#### Logicals
```{r vec_lgl}
lgl1 <- TRUE
lgl2 <- T #abbreviation for TRUE
lgl3 <- FALSE
lgl4 <- F #abbreviation for FALSE
```
#### Doubles
```{r vec_dbl}
# integer, decimal, scientific, or hexidecimal format
dbl1 <- 1
dbl2 <- 1.234 # decimal
dbl3 <- 1.234e0 # scientific format
dbl4 <- 0xcafe # hexidecimal format
```
#### Integers
Integers must be followed by L and cannot have fractional values
```{r vec_int}
int1 <- 1L
int2 <- 1234L
int3 <- 1234e0L
int4 <- 0xcafeL
```
<details>
<summary>Pop Quiz: Why "L" for integers?</summary>
Wickham notes that the use of `L` dates back to the **C** programming language and its "long int" type for memory allocation.
</details>
#### Strings
Strings can use single or double quotes and special characters are escaped with \
```{r vec_str}
str1 <- "hello" # double quotes
str2 <- 'hello' # single quotes
str3 <- "مرحبًا" # Unicode
str4 <- "\U0001f605" # sweaty_smile
```
### Longer
There are several ways to make longer vectors:
**1. With single values** inside c() for combine.
```{r long_single}
lgl_var <- c(TRUE, FALSE)
int_var <- c(1L, 6L, 10L)
dbl_var <- c(1, 2.5, 4.5)
chr_var <- c("these are", "some strings")
```
![Image Credit: Advanced R](images/vectors/atomic.png)
**2. With other vectors**
```{r long_vec}
c(c(1, 2), c(3, 4)) # output is not nested
```
<details>
<summary>Side Quest: rlang</summary>
`{rlang}` has [vector constructor functions too](https://rlang.r-lib.org/reference/vector-construction.html):
- `rlang::lgl(...)`
- `rlang::int(...)`
- `rlang::dbl(...)`
- `rlang::chr(...)`
They look to do both more and less than `c()`.
- More:
- Enforce type
- Splice lists
- More types: `rlang::bytes()`, `rlang::cpl(...)`
- Less:
- Stricter rules on names
Note: currently has `questioning` lifecycle badge, since these constructors may get moved to `vctrs`
</details>
### Type and Length
We can determine the type of a vector with `typeof()` and its length with `length()`
```{r type_length, echo = FALSE}
# typeof(lgl_var)
# typeof(int_var)
# typeof(dbl_var)
# typeof(chr_var)
#
# length(lgl_var)
# length(int_var)
# length(dbl_var)
# length(chr_var)
var_names <- c("lgl_var", "int_var", "dbl_var", "chr_var")
var_values <- c("TRUE, FALSE", "1L, 6L, 10L", "1, 2.5, 4.5", "'these are', 'some strings'")
var_type <- c("logical", "integer", "double", "character")
var_length <- c(2, 3, 3, 2)
type_length_df <- data.frame(var_names, var_values, var_type, var_length)
# make gt table
type_length_df |>
gt() |>
cols_align(align = "center") |>
cols_label(
var_names ~ "name",
var_values ~ "value",
var_type ~ "typeof()",
var_length ~ "length()"
) |>
tab_header(
title = "Types of Atomic Vectors",
subtitle = ""
) |>
tab_footnote(
footnote = "Source: https://adv-r.hadley.nz/index.html",
locations = cells_title(groups = "title")
) |>
tab_style(
style = list(cell_fill(color = "#F9E3D6")),
locations = cells_body(columns = var_type)
) |>
tab_style(
style = list(cell_fill(color = "lightcyan")),
locations = cells_body(columns = var_length)
)
```
<details>
<summary>Side Quest: Penguins</summary>
```{r}
typeof(penguins$species)
class(penguins$species)
typeof(species_unlist)
class(species_unlist)
typeof(species_pull)
class(species_pull)
```
</details>
### Missing values
#### Contagion
For most computations, an operation over values that includes a missing value yields a missing value (unless you're careful)
```{r na_contagion}
# contagion
5*NA
sum(c(1, 2, NA, 3))
```
#### Exceptions
```{r na_exceptions, eval = FALSE}
NA ^ 0
#> [1] 1
NA | TRUE
#> [1] TRUE
NA & FALSE
#> [1] FALSE
```
#### Innoculation
```{r na_innoculation, eval = FALSE}
sum(c(1, 2, NA, 3), na.rm = TRUE)
# output: 6
```
To search for missing values use `is.na()`
```{r na_search, eval = FALSE}
x <- c(NA, 5, NA, 10)
x == NA
# output: NA NA NA NA [BATMAN!]
```
```{r na_search_better, eval = FALSE}
is.na(x)
# output: TRUE FALSE TRUE FALSE
```
<details>
<summary>Side Quest: NA Types</summary>
Each type has its own NA type
- Logical: `NA`
- Integer: `NA_integer`
- Double: `NA_double`
- Character: `NA_character`
This may not matter in many contexts.
But this does matter for operations where types matter like `dplyr::if_else()`.
</details>
### Testing
**What type of vector `is.*`() it?**
Test data type:
- Logical: `is.logical()`
- Integer: `is.integer()`
- Double: `is.double()`
- Character: `is.character()`
**What type of object is it?**
Don't test objects with these tools:
- `is.vector()`
- `is.atomic()`
- `is.numeric()`
They don’t test if you have a vector, atomic vector, or numeric vector; you’ll need to carefully read the documentation to figure out what they actually do (preview: *attributes*)
<details>
<summary>Side Quest: rlang</summary>
Instead, maybe, use `{rlang}`
- `rlang::is_vector`
- `rlang::is_atomic`
```{r test_rlang}
# vector
rlang::is_vector(c(1, 2))
rlang::is_vector(list(1, 2))
# atomic
rlang::is_atomic(c(1, 2))
rlang::is_atomic(list(1, "a"))
```
See more [here](https://rlang.r-lib.org/reference/type-predicates.html)
</details>
### Coercion
* R follows rules for coercion: character → double → integer → logical
* R can coerce either automatically or explicitly
#### **Automatic**
Two contexts for automatic coercion:
1. Combination
2. Mathematical
##### Coercion by Combination:
```{r coerce_c}
str(c(TRUE, "TRUE"))
```
##### Coercion by Mathematical operations:
```{r coerce_math}
# imagine a logical vector about whether an attribute is present
has_attribute <- c(TRUE, FALSE, TRUE, TRUE)
# number with attribute
sum(has_attribute)
```
#### **Explicit**
<!--
Use `as.*()`
- Logical: `as.logical()`
- Integer: `as.integer()`
- Double: `as.double()`
- Character: `as.character()`
-->
```{r explicit_coercion, echo = FALSE}
# dbl_var
# as.integer(dbl_var)
# lgl_var
# as.character(lgl_var)
var_names <- c("lgl_var", "int_var", "dbl_var", "chr_var")
var_values <- c("TRUE, FALSE", "1L, 6L, 10L", "1, 2.5, 4.5", "'these are', 'some strings'")
as_logical <- c("TRUE FALSE", "TRUE TRUE TRUE", "TRUE TRUE TRUE", "NA NA")
as_integer <- c("1 0", "1 6 10", "1 2 4", 'NA_integer')
as_double <- c("1 0", "1 6 10", "1.0 2.5 4.5", 'NA_double')
as_character <- c("'TRUE' 'FALSE'", "'1' '6' '10'", "'1' '2.5' '4.5'", "'these are', 'some strings'")
coercion_df <- data.frame(var_names, var_values, as_logical, as_integer, as_double, as_character)
coercion_df |>
gt() |>
cols_align(align = "center") |>
cols_label(
var_names ~ "name",
var_values ~ "value",
as_logical ~ "as.logical()",
as_integer ~ "as.integer()",
as_double ~ "as.double()",
as_character ~ "as.character()"
) |>
tab_header(
title = "Coercion of Atomic Vectors",
subtitle = ""
) |>
tab_footnote(
footnote = "Source: https://adv-r.hadley.nz/index.html",
locations = cells_title(groups = "title")
) |>
tab_style(
style = list(cell_fill(color = "#F9E3D6")),
locations = cells_body(columns = c(as_logical, as_double))
) |>
tab_style(
style = list(cell_fill(color = "lightcyan")),
locations = cells_body(columns = c(as_integer, as_character))
)
```
But note that coercion may fail in one of two ways, or both:
- With warning/error
- NAs
```{r coerce_error}
as.integer(c(1, 2, "three"))
```
### Exercises
1. How do you create raw and complex scalars?
<details><summary>Answer(s)</summary>
```{r, eval = FALSE}
as.raw(42)
#> [1] 2a
charToRaw("A")
#> [1] 41
complex(length.out = 1, real = 1, imaginary = 1)
#> [1] 1+1i
```
</details>
2. Test your knowledge of the vector coercion rules by predicting the output of the following uses of c():
```{r, eval = FALSE}
c(1, FALSE)
c("a", 1)
c(TRUE, 1L)
```
<details><summary>Answer(s)</summary>
```{r, eval = FALSE}
c(1, FALSE) # will be coerced to double -> 1 0
c("a", 1) # will be coerced to character -> "a" "1"
c(TRUE, 1L) # will be coerced to integer -> 1 1
```
</details>
3. Why is `1 == "1"` true? Why is `-1 < FALSE` true? Why is `"one" < 2` false?
<details><summary>Answer(s)</summary>
These comparisons are carried out by operator-functions (==, <), which coerce their arguments to a common type. In the examples above, these types will be character, double and character: 1 will be coerced to "1", FALSE is represented as 0 and 2 turns into "2" (and numbers precede letters in lexicographic order (may depend on locale)).
</details>
4. Why is the default missing value, NA, a logical vector? What’s special about logical vectors?
<details><summary>Answer(s)</summary>
The presence of missing values shouldn’t affect the type of an object. Recall that there is a type-hierarchy for coercion from character → double → integer → logical. When combining `NA`s with other atomic types, the `NA`s will be coerced to integer (`NA_integer_`), double (`NA_real_`) or character (`NA_character_`) and not the other way round. If `NA` were a character and added to a set of other values all of these would be coerced to character as well.
</details>
5. Precisely what do `is.atomic()`, `is.numeric()`, and `is.vector()` test for?
<details><summary>Answer(s)</summary>
The documentation states that:
* `is.atomic()` tests if an object is an atomic vector (as defined in *Advanced R*) or is `NULL` (!).
* `is.numeric()` tests if an object has type integer or double and is not of class `factor`, `Date`, `POSIXt` or `difftime`.
* `is.vector()` tests if an object is a vector (as defined in *Advanced R*) or an expression and has no attributes, apart from names.
Atomic vectors are defined in *Advanced R* as objects of type logical, integer, double, complex, character or raw. Vectors are defined as atomic vectors or lists.
</details>
## Attributes
Attributes are name-value pairs that attach metadata to an object(vector).
* **Name-value pairs**: attributes have a name and a value
* **Metadata**: not data itself, but data about the data
### How?
#### Getting and Setting
Three functions:
1. retrieve and modify single attributes with `attr()`
2. retrieve en masse with `attributes()`
3. set en masse with `structure()`
**Single attribute**
Use `attr()`
```{r attr_single}
# some object
a <- c(1, 2, 3)
# set attribute
attr(x = a, which = "attribute_name") <- "some attribute"
# get attribute
attr(a, "attribute_name")
```
**Multiple attributes**
To set multiple attributes, use `structure()` To get multiple attributes, use `attributes()`
```{r attr_multiple_not_from_textbook, echo = FALSE}
# b <- c(4, 5, 6)
#
# # set
# b <- structure(
# .Data = b,
# attrib1_name = "first_attribute",
# attrib2_name = "second_attribute"
# )
#
# # get
# attributes(b)
# str(attributes(b))
```
```{r attr_multiple, eval = FALSE}
a <- 1:3
attr(a, "x") <- "abcdef"
attr(a, "x")
#> [1] "abcdef"
attr(a, "y") <- 4:6
str(attributes(a))
#> List of 2
#> $ x: chr "abcdef"
#> $ y: int [1:3] 4 5 6
# Or equivalently
a <- structure(
1:3,
x = "abcdef",
y = 4:6
)
str(attributes(a))
#> List of 2
#> $ x: chr "abcdef"
#> $ y: int [1:3] 4 5 6
```
![Image Credit: Advanced R](images/vectors/attr.png)
### Why
Three particularly important attributes:
1. **names** - a character vector giving each element a name
2. **dimension** - (or dim) turns vectors into matrices and arrays
3. **class** - powers the S3 object system (we'll learn more about this in chapter 13)
Most attributes are lost by most operations. Only two attributes are routinely preserved: names and dimension.
#### Names
~~Three~~ Four ways to name:
```{r names}
# (1) When creating it:
x <- c(A = 1, B = 2, C = 3)
x
# (2) By assigning a character vector to names()
y <- 1:3
names(y) <- c("a", "b", "c")
y
# (3) Inline, with setNames():
z <- setNames(1:3, c("a", "b", "c"))
z
```
![proper diagram](images/vectors/attr-names-1.png)
```{r names_via_rlang}
# (4) By setting names--with {rlang}
a <- 1:3
rlang::set_names(
x = a,
nm = c("a", "b", "c")
)
```
![simplified diagram](images/vectors/attr-names-2.png)
* You can remove names from a vector by using `x <- unname(x)` or `names(x) <- NULL`.
* Thematically but not directly related: labelled class vectors with `haven::labelled()`
#### Dimensions
Create matrices and arrays with `matrix()` and `array()`, or by using the assignment form of `dim()`:
```{r dimensions}
# Two scalar arguments specify row and column sizes
x <- matrix(1:6, nrow = 2, ncol = 3)
x
# One vector argument to describe all dimensions
y <- array(1:24, c(2, 3, 4)) # rows, columns, no of arrays
y
# You can also modify an object in place by setting dim()
z <- 1:6
dim(z) <- c(2, 3) # rows, columns
z
a <- 1:24
dim(a) <- c(2, 3, 4) # rows, columns, no of arrays
a
```
##### Functions for working with vectors, matrices and arrays:
Vector | Matrix | Array
:----- | :---------- | :-----
`names()` | `rownames()`, `colnames()` | `dimnames()`
`length()` | `nrow()`, `ncol()` | `dim()`
`c()` | `rbind()`, `cbind()` | `abind::abind()`
— | `t()` | `aperm()`
`is.null(dim(x))` | `is.matrix()` | `is.array()`
* **Caution**: A vector without a `dim` attribute set is often thought of as 1-dimensional, but actually has `NULL` dimensions.
* One dimension?
```{r examples_of_1D, eval = FALSE}
str(1:3) # 1d vector
#> int [1:3] 1 2 3
str(matrix(1:3, ncol = 1)) # column vector
#> int [1:3, 1] 1 2 3
str(matrix(1:3, nrow = 1)) # row vector
#> int [1, 1:3] 1 2 3
str(array(1:3, 3)) # "array" vector
#> int [1:3(1d)] 1 2 3
```
### Exercises
1. How is `setNames()` implemented? How is `unname()` implemented? Read the source code.
<details><summary>Answer(s)</summary>
`setNames()` is implemented as:
```{r, eval = FALSE}
setNames <- function(object = nm, nm) {
names(object) <- nm
object
}
```
Because the data argument comes first, `setNames()` also works well with the magrittr-pipe operator. When no first argument is given, the result is a named vector (this is rather untypical as required arguments usually come first):
```{r, eval = FALSE}
setNames( , c("a", "b", "c"))
#> a b c
#> "a" "b" "c"
```
`unname()` is implemented in the following way:
```{r, eval = FALSE}
unname <- function(obj, force = FALSE) {
if (!is.null(names(obj)))
names(obj) <- NULL
if (!is.null(dimnames(obj)) && (force || !is.data.frame(obj)))
dimnames(obj) <- NULL
obj
}
```
`unname()` removes existing names (or dimnames) by setting them to `NULL`.
</details>
2. What does `dim()` return when applied to a 1-dimensional vector? When might you use `NROW()` or `NCOL()`?
<details><summary>Answer(s)</summary>
> dim() will return NULL when applied to a 1d vector.
One may want to use `NROW()` or `NCOL()` to handle atomic vectors, lists and NULL values in the same way as one column matrices or data frames. For these objects `nrow()` and `ncol()` return NULL:
```{r, eval = FALSE}
x <- 1:10
# Return NULL
nrow(x)
#> NULL
ncol(x)
#> NULL
# Pretend it's a column vector
NROW(x)
#> [1] 10
NCOL(x)
#> [1] 1
```
</details>
3. How would you describe the following three objects? What makes them different from `1:5`?
```{r}
x1 <- array(1:5, c(1, 1, 5))
x2 <- array(1:5, c(1, 5, 1))
x3 <- array(1:5, c(5, 1, 1))
```
<details><summary>Answer(s)</summary>
```{r, eval = FALSE}
x1 <- array(1:5, c(1, 1, 5)) # 1 row, 1 column, 5 in third dim.
x2 <- array(1:5, c(1, 5, 1)) # 1 row, 5 columns, 1 in third dim.
x3 <- array(1:5, c(5, 1, 1)) # 5 rows, 1 column, 1 in third dim.
```
</details>
4. An early draft used this code to illustrate `structure()`:
```{r, eval = FALSE}
structure(1:5, comment = "my attribute")
#> [1] 1 2 3 4 5
```
But when you print that object you don’t see the comment attribute. Why? Is the attribute missing, or is there something else special about it?
<details><summary>Answer(s)</summary>
The documentation states (see `?comment`):
> Contrary to other attributes, the comment is not printed (by print or print.default).
Also, from `?attributes:`
> Note that some attributes (namely class, comment, dim, dimnames, names, row.names and tsp) are treated specially and have restrictions on the values which can be set.
We can retrieve comment attributes by calling them explicitly:
```{r, eval = FALSE}
foo <- structure(1:5, comment = "my attribute")
attributes(foo)
#> $comment
#> [1] "my attribute"
attr(foo, which = "comment")
#> [1] "my attribute"
```
</details>
## **Class** - S3 atomic vectors
![](images/vectors/summary-tree-s3-1.png)
Credit: [Advanced R](https://adv-r.hadley.nz/index.html) by Hadley Wickham
**Having a class attribute turns an object into an S3 object.**
What makes S3 atomic vectors different?
1. behave differently from a regular vector when passed to a generic function
2. often store additional information in other attributes
Four important S3 vectors used in base R:
1. **Factors** (categorical data)
2. **Dates**
3. **Date-times** (POSIXct)
4. **Durations** (difftime)
### Factors
A factor is a vector used to store categorical data that can contain only predefined values.
Factors are integer vectors with:
- Class: "factor"
- Attributes: "levels", or the set of allowed values
```{r factor}
colors = c('red', 'blue', 'green','red','red', 'green')
# Build a factor
a_factor <- factor(
# values
x = colors,
# exhaustive list of values
levels = c('red', 'blue', 'green', 'yellow')
)
```
```{r factor_table}
# Useful when some possible values are not present in the data
table(colors)
table(a_factor)
# - type
typeof(a_factor)
class(a_factor)
# - attributes
attributes(a_factor)
```
#### Custom Order
Factors can be ordered. This can be useful for models or visualizations where order matters.
```{r factor_ordered}
values <- c('high', 'med', 'low', 'med', 'high', 'low', 'med', 'high')
ordered_factor <- ordered(
# values
x = values,
# levels in ascending order
levels = c('low', 'med', 'high')
)
# Inspect
ordered_factor
table(values)
table(ordered_factor)
```
### Dates
Dates are:
- Double vectors
- With class "Date"
- No other attributes
```{r dates}
notes_date <- Sys.Date()
# type
typeof(notes_date)
# class
attributes(notes_date)
```
The double component represents the number of days since since the [Unix epoch](https://en.wikipedia.org/wiki/Unix_time) `1970-01-01`
```{r days_since_1970}
date <- as.Date("1970-02-01")
unclass(date)
```
### Date-times
There are 2 Date-time representations in base R:
- POSIXct, where "ct" denotes *calendar time*
- POSIXlt, where "lt" designates *local time*
<!--
Just for fun:
"How to pronounce 'POSIXct'?"
https://www.howtopronounce.com/posixct
-->
We'll focus on POSIXct because:
- Simplest
- Built on an atomic (double) vector
- Most appropriate for use in a data frame
Let's now build and deconstruct a Date-time
```{r date_time}
# Build
note_date_time <- as.POSIXct(
x = Sys.time(), # time
tz = "America/New_York" # time zone, used only for formatting
)
# Inspect
note_date_time
# - type
typeof(note_date_time)
# - attributes
attributes(note_date_time)
structure(note_date_time, tzone = "Europe/Paris")
```
```{r date_time_format}
date_time <- as.POSIXct("2024-02-22 12:34:56", tz = "EST")
unclass(date_time)
```
### Durations
Durations represent the amount of time between pairs of dates or date-times.
- Double vectors
- Class: "difftime"
- Attributes: "units", or the unit of duration (e.g., weeks, hours, minutes, seconds, etc.)
```{r durations}
# Construct
one_minute <- as.difftime(1, units = "mins")
# Inspect
one_minute
# Dissect
# - type
typeof(one_minute)
# - attributes
attributes(one_minute)
```
```{r durations_math}
time_since_01_01_1970 <- notes_date - date
time_since_01_01_1970
```
See also:
- [`lubridate::make_difftime()`](https://lubridate.tidyverse.org/reference/make_difftime.html)
- [`clock::date_time_build()`](https://clock.r-lib.org/reference/date_time_build.html)
### Exercises
1. What sort of object does `table()` return? What is its type? What attributes does it have? How does the dimensionality change as you tabulate more variables?