Vectors in R

Create a Vector

x<- c(1, 6, 4, 10, -2)  ##vector with defined set of values using c() means concatenate
x
## [1]  1  6  4 10 -2
class(x)  ##class() will return the data type of object
## [1] "numeric"
y<-1:10   ##Vector with 1 to 10 continuous Numbers
y
##  [1]  1  2  3  4  5  6  7  8  9 10
class(y)
## [1] "integer"
z<-seq(1,20,by=2) ##Vector starts from 1 end at 20  leave by 2 (e.g:1,3,5...)
z
##  [1]  1  3  5  7  9 11 13 15 17 19
class(z)
## [1] "numeric"
k <- rep(1,10) #Create a repetitive patterneg:1,1,1... 10 times
k
##  [1] 1 1 1 1 1 1 1 1 1 1

Vector operations

sum(x) ## sums the values in the vector
## [1] 19
length(x) ## produces the number of values in the vector, ie its length
## [1] 5
mean(x) ## the average (mean)
## [1] 3.8
var(x) ## the sample variance of the values in the vector (has n-1 in denominator)
## [1] 21.2
sd(x) ## the sample standard deviation of the values in the vector (square root of the sample variance)
## [1] 4.604346
max(x) ## the largest value in the vector
## [1] 10
min(x) ## the smallest number in the vector
## [1] -2
median(x) ## the sample median
## [1] 4
y <- sort(x) ## the values arranged in ascending order
y
## [1] -2  1  4  6 10
marks <- c(16, 9, 13, 5, 2, 17, 14)
last <- tail(marks, 1)
last   
## [1] 14
last_n <- tail(marks, 2) ##Last two elements
last_n   
## [1] 17 14
(last <5 | last >10)   # Is last under 5 or above 10?
## [1] TRUE
(last > 15 & last < 20)# Is last between 15 (exclusive) and 20 (inclusive)?
## [1] FALSE
(last>0 & last<5 )|(last>10 & last<15)# Is last between 0 and 5 or between 10 and 15?
## [1] TRUE

Vector Arthematic

##Adding elements to vector:

x <- c(1:10)
x
##  [1]  1  2  3  4  5  6  7  8  9 10
y <- 10
x + y
##  [1] 11 12 13 14 15 16 17 18 19 20
2 + 3 * x #Note the order of operations
##  [1]  5  8 11 14 17 20 23 26 29 32
(2 + 3) * x #See the difference
##  [1]  5 10 15 20 25 30 35 40 45 50
sqrt(x) #Square roots
##  [1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751
##  [8] 2.828427 3.000000 3.162278
x %% 4 #This is the integer divide (modulo) operation
##  [1] 1 2 3 0 1 2 3 0 1 2
y <- 3 + 2i #R does complex numbers
Re(y) #The real part of the complex number
## [1] 3
Im(y) #The imaginary part of the complex number
## [1] 2
x * y
##  [1]  3+ 2i  6+ 4i  9+ 6i 12+ 8i 15+10i 18+12i 21+14i 24+16i 27+18i 30+20i