Section 20 Vector Subsetting

20.1 Subset a vector

Example vector: x <- c(1:5); names(x) <- letters[1:5]

Index Explanation Example.
[i] Single square bracket with apprpriate index for the element(s) x[1:2]
Positive integer Select the elements corresponding to the integer value x[2]; x[c(1,3)]
Negative integer Remove the elements corresponding to the integer value x[-2]; x[-c(1,3)]
Zero Select no element x[0]
Blank Select all elements x[]
Logical values Select the element corresponding to the logical value TRUE x[c(T,F,T,T,F)]
Names Select the element corresponding to the named value x[a]

20.2 Example

x <- c(1:5); names(x) <- letters[1:5]
x

x[1:2]
x[2]
x[c(1,3)]
x[-2]
x[-c(1,3)]
x[0]
x[]
x[c(T,F,T,T,F)]
x['a']


x[2]
x[c(1,3)]
x[2:3]
x[2,3] # Error

x[-2]
x[-c(1,3)]
x[-4]

x[0]

x[]

x[c(T,F,T,T,F)]
x[TRUE]
x[TRUE,FALSE] # Error
x[c(TRUE,FALSE)]

x['a']
x['a','b']  # Error
x[c('a','b')]
x[c('a','e')]

x[x>3]
x[x<3]
x[x>=3]
x[(x>1 & x<4)]
x[(x<3 | x>4)]