R Vector

Vector in R is contain element with same data type. To create a vector or object c() function is use. Here is sample of R vector :

schar <- c("a","b","c")  ## assign character Vector
snum <- c(1,2,3) ## assign numerical Vector
slog <- c(FALSE, TRUE) ## assign logical Vector
scomp <- c(1+2i, 3+4i) ## assign complex Vector
sint <- 1:20 ## assign integer vector

Create Vector

Each elements of numeric vector can be filter to meet certain condition.

> num_vec <- c(23,0,1,4,5)
> num_vec
[1] 23  0  1  4  5
> testcon <- num_vec > 4
> testcon
[1]  TRUE FALSE FALSE FALSE  TRUE
>

Use “paste” function to join character element vector.

> mystatement <- c("Hello", "beautiful", "world")
> mystatement
[1] "Hello"     "beautiful" "world"   
> paste(mystatement, collapse = " ")
[1] "Hello beautiful world"

Print length of Vector

> length(c("Hello", "beautiful", "world"))
[1] 3

Element vector can be access by using “[index]” brackets.

> vec_month <- c("Jan","Feb","March","April","May","June","July","Aug","Sep","Oct","Nov","Dec")
> thesixth<-vec_month[c(6)]
> thesixth
[1] "June"
> thetwelve<-vec_month[c(12)]
> thetwelve
[1] "Dec"