Web EndMemo

R Vector Data Type


R vector data type is similar to array of other programming languages. It's consisted of an ordered number of elements. The elements can be numeric (integer, double), logical, character, complex, or raw.


Vector assignment:
>v <- c(2,3,5.5,7.1,2.1,3)
>v
[1] 2.0 3.0 5.5 7.1 2.1 3.0

Other vector assignment syntax:
>assign("v",c(2,3,5.5,7.1,2.1,3))
>c(2,3,5.5,7.1,2.1,3) -> v

The 1st element of R vector is indexed as 1, not 0 as some other programming languages.
Access the 3rd elements of vector v:
>v[3]
[1] 2

R can operate vector like a single element. e.g.
>1/v
[1] 0.5000000 0.3333333 0.1818182 0.1408451 0.4761905 0.3333333
>2+v
[1] 4.0 5.0 7.5 9.1 4.1 5.0
>v2 <- v + 1/v + 5
>v2
[1]  7.500000  8.333333 10.681818 12.240845  7.576190  8.333333

Judge a data structure is vector or not:
>is.vector(v)
[1] TRUE
>is.vector(3,mode="any")
[1] TRUE
>is.vector(3,mode="list")
[1] FALSE

Under default mode "any", logical, number, character are treated as vectors with length 1. It will retrun FALSE only if the object being judged has name attribute. Under mode "numeric", is.vector will return true for vectors of types integer or double. and mode "integer" can only be true for vectors of type integer.


Other methods for generating regular vectors:
>v <- 1:10
>v
[1]  1  2  3  4  5  6  7  8  9 10
>v <- rep(2,10)
>v
[1] 2 2 2 2 2 2 2 2 2 2
>v <- seq(1,5,by=0.5)
>v
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
>v <- seq(length=10,from=1,by=0.5)
>v
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5