Saturday, August 13, 2011

R - subscripting 2

subsetting with character indices - vectors and lists

  • extract elements of named vectors, lists
named.x <- 1:10  # produce a vector containing the numbers 1...10
named.x   #  has no names yet
 [1]  1  2  3  4  5  6  7  8  9 10
  • if the object has no names, NAs are produced
named.x["one"]
[1] NA
  • name the vector:
names(named.x) <- c("one","two","three","four","five","six","seven","eight","nine","ten")
named.x
  one   two three  four  five   six seven eight  nine   ten 
    1     2     3     4     5     6     7     8     9    10
  • now it works
named.x["one"]
one 
  1
  • if names are duplicated only the first match is returned (the value with the lowest index)
names(named.x)<-rep(c("one","two","three","four","five"),rep(2,5))
named.x
  one   one   two   two three three  four  four  five  five 
    1     2     3     4     5     6     7     8     9    10
named.x[c("one","two","three")]
  one   two three 
    1     3     5
  • NA is returned if a name do not match any element
named.x["twenty"]
<NA> 
  NA
  • NA is returned if a subscript is character NA
named.x[c("one",NA,"three")]
  one  <NA> three 
    1    NA     5
  • to find all occurences one can use %in% and then subset with the logical vector (you can do this in one step)
named.x[names(named.x) %in% c("one","two")]
one one two two 
  1   2   3   4

No comments :

Post a Comment