Vectors: Vector calculus in R
Selection of components, and assignment of values
Selection of components and subvectors You can select components of vectors in different ways. We give a few examples showing that indexing starts at 1 and that there a smart methods to create some vectors.
> v <- 6:10; v
[1] 6 7 8 9 10
> v[2] # a single component
[1] 7
> v[c(2,4)] # several components
[1] 7 9
> v[2:4] # a subvector
[1] 7 8 9
> v[2:length(v)] # everything except the first component
[1] 7 8 9 10
> v[-1] # everything except the first component
[1] 7 8 9 10
> v[1:length(v)-1] # everything except the last component
[1] 6 7 8 9
> v[-length(v)] # everything except the last component
[1] 6 7 8 9
Selection via logical expressions You can also use logical indexing (with values TRUE and FALSE) to select components of vectors. You need relational operators for this, such as the ones in the table below.
== | equal to | != | not equal to |
< | less than | > | greater than |
<= | less than or equal to | >= | greater than or equal to |
> v <- 5:10; v
[1] 5 6 7 8 9 10
> lv <- v>8; lv # vector values true/false if the condition is indeed/not met
[1] FALSE FALSE FALSE FALSE TRUE TRUE
> v[lv] # selection of components
[1] 9 10
> i <- (1:length(v))[v<8]; i # selection of indices
[1] 1 2 3
> v[i] # selection of components
[1] 5 6 7
Assignment Components to which you refer can also be assigned new values.
> v <- 5:10; v
[1] 5 6 7 8 9 10
> v[1] <- 4; v # 1st component set to 4
[1] 4 6 7 8 9 10
> v[c(1,2)] <- 5; v # first 2 components set to 5
[1] 5 5 7 8 9 10 > v[-2] # 2nd component deleted in result, but not in source
[1] 5 7 8 9 10
> v
[1] 5 5 7 8 9 10
> v[1:length(v)] <- 1; v # all components set to 1
[1] 1 1 1 1 1 1
By assignments you cannot change the structure. In the example below, we give the vector is an extra component via the append
function, but this is not done in-line, that is to say, the structure of the vector does not change (an assignment is required for this purpose). By the way, this is not a recommended approach. Pre-reserving ample space for components in a vector using the zero construction and then filling the data vector with values by assignments is a better way to collect data in Python experiments such as response times to stimuli.
> v <- 5:7; v # vector of length 3
[1] 5 6 7
> c(v, 8) # no assignment or extension
[1] 5 6 7 8
> v
[1] 5 6 7
> v <- c(v, 8); v # vector of length 4
[1] 5 6 7 8