## B.6 Named Vectors

### B.6.1 Creating Named Vectors

Vectors in R can be named – each element can be assigned a string label.

x <- c(20, 40, 99, 30, 10)
names(x) <- c("a", "b", "c", "d", "e")
x # a named vector
##  a  b  c  d  e
## 20 40 99 30 10

Other ways to create named vectors include:

c(a=1, b=2, c=3)
## a b c
## 1 2 3
structure(1:3, names=c("a", "b", "c"))
## a b c
## 1 2 3

For instance, the summary() function returns a named vector:

summary(x) # NAMED vector, we don't want this here yet
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
##    10.0    20.0    30.0    39.8    40.0    99.0

This gives the minimum, 1st quartile (25%-quantile), Median (50%-quantile), aritmetic mean, 3rd quartile (75%-quantile) and maximum.

Note that x is still a numeric vector, we can perform various operations on it as usual:

sum(x)
## [1] 199
x[x>3]
##  a  b  c  d  e
## 20 40 99 30 10

Names can be dropped by calling:

unname(x)
## [1] 20 40 99 30 10
as.numeric(x) # we need to know the type of x though
## [1] 20 40 99 30 10

### B.6.2 Subsetting Named Vectors with Character String Indices

It turns out that extracting elements from a named vector can also be performed by means of a vector of character string indices:

x[c("a", "d", "b")]
##  a  d  b
## 20 30 40
summary(x)[c("Median", "Mean")]
## Median   Mean
##   30.0   39.8