The Art of R Programming

(WallPaper) #1

2.11 Vector Element Names......................................................


The elements of a vector can optionally be given names. For example, say
we have a 50-element vector showing the population of each state in the
United States. We could name each element according to its state name,
such as"Montana"and"New Jersey". This in turn might lead to naming
points in plots, and so on.
We can assign or query vector element names via thenames()function:

> x <- c(1,2,4)
> names(x)
NULL
> names(x) <- c("a","b","ab")
> names(x)
[1] "a" "b" "ab"
>x
abab
124

We can remove the names from a vector by assigning NULL:

> names(x) <- NULL
>x
[1]124

We can even reference elements of the vector by name:

> x <- c(1,2,4)
> names(x) <- c("a","b","ab")
> x["b"]
b
2

2.12 More on c()
In this section, we’ll discuss a couple of miscellaneous facts related to the
concatenate function,c(), that often come in handy.
If the arguments you pass toc()are of differing modes, they will be
reduced to a type that is the lowest common denominator, as follows:

> c(5,2,"abc")
[1] "5" "2" "abc"
> c(5,2,list(a=1,b=4))
[[1]]
[1] 5

[[2]]
[1] 2

56 Chapter 2

Free download pdf