"steve" # scalar
[1] "steve"
9 # scalar
[1] 9
length(9)
[1] 1
KIND training materials by KIND learning network is licensed under CC BY-SA 4.0
November 21, 2024
This was about the vectors chapter in Advanced R (2nd ed). It’s mainly about how vectors and lists work.
There are a few odd extras, but nearly all vectors in the wild can be taxonomised like this:
1234L
, 1e4L
, or 0xcafeL
0.1234
), scientific (1.23e4
), hex (0xcafe
), Inf
, -Inf
, and NaN
NULL
(a 0-length vector)c()
[1] TRUE FALSE
[1] "nested" "vectors" "get" "flattened"
[1] "character"
[1] "this" "gets completely" "flattened"
[[1]]
[1] "this"
[[2]]
[[2]][[1]]
[1] "gets"
[[2]][[2]]
[1] "not"
[[2]][[3]]
[1] "at all"
[[3]]
[1] "flattened"
[1] TRUE TRUE
[[1]]
[1] "c"
[[2]]
[1] 1
character(0)
list()
NULL
[1] TRUE
This is a big issue because many R functions will coerce, and it can cause serious trouble. There’s a bit of discussion about the ordering, where character is basically the ground state/most basic, then double, then integer, then logical. So logical only gets made from logical inputs, integer from logical or integer, double from double, or integer, or logical, and character from anything.
[1] 1
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] NA
[1] "logical"
[1] "logical"
[1] "integer"
[1] "double"
[1] "character"
[1] 1 1 NA
[1] "NA"
[1] "NA"
This area is rich in false friends - functions with plausible-sounding names that do something unusual and not entirely what you might expect from their name:
Vectors can have attributes - like names. Most attributes are pretty fragile, and get removed very easily:
[1] "double"
[1] "one" "two" "three"
$names
[1] "one" "two" "three"
[1] "one" "two" "three"
attr(testy4, "supernames") <- c("one but secret", "two but secret", "three but secret")
attributes(testy4)
$names
[1] "one" "two" "three"
$supernames
[1] "one but secret" "two but secret" "three but secret"
List of 2
$ names : chr [1:3] "one" "two" "three"
$ supernames: chr [1:3] "one but secret" "two but secret" "three but secret"