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.
>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 > v[v>5][1] 5.5 7.1
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 >v2 <- vector()#declare an emplty vector
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] 5.5 >length(v)#get vector v's length [1] 6
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
> x <- array(1:9,c(3,3)) > x[,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > as.vector(x)[1] 1 2 3 4 5 6 7 8 9
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.
>v <- 1:10 >v
[1] 1 2 3 4 5 6 7 8 9 10 >v <- v[3:length(v)] >v[1] 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
> v <- c(2,3,5.5,7.1,2.1,3) > 3 %in% v[1] TRUE