Named Elements within Vectors

It is often useful to have the values in a vector labelled in some way. For instance, if our data are counts of 0, 1, 2, ... occurrences in a vector called counts

(counts<-c(25,12,7,4,6,2,1,0,2))

[1] 25 12 7 4 6 2 1 0 2

so that there were 25 zeros, 12 ones and so on, it would be useful to name each of the counts with the relevant number 0 to 8:

names(counts)<-0:8

Now when we inspect the vector called counts we see both the names and the frequencies:

counts

 0  1 2 3 4 5 6 7 8
25 12 7 4 6 2 1 0 2

If you have computed a table of counts, and you want to remove the names, then use the as.vector function like this:

(st<-table(rpois(2000,2.3)))

  0 1   2     3 4     5  6  7 8 9
205 455 510 431 233 102 43 13 7 1

as.vector(st)

[1] 205  455 510 431  233 102  43 13 7 1

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.