1. Some common vector operations.

1.1 Vector arithmetic

# Recall further that scalars are actually one-element vectors. So, we can add vectors, and the + operation will be applied element-wise.

x<-c(1,2,3) # create a vector x
x+ c(4,5,6) # A way to add two vectors (note: we can have any operend in place of + )
## [1] 5 7 9
"+"(2,3) # Note that the operends are considered as functions in R. So, can be used this way.
## [1] 5

1.2 Vectorized Operations

One of the most effective ways to achieve speed in R code is to use operations that are vectorized, meaning that a function applied to a vector is actually applied individually to each element.

z<- c(1,3,5,6,7)
sqrt(z)# Here square root is applied to all elements in the vector z
## [1] 1.000000 1.732051 2.236068 2.449490 2.645751

Note: we can use defined function on vectors.

1.3 Modulus division

x<-c(10,6,7)
x%%c(5,2,2) # returns the remainder from the division
## [1] 0 0 1

1.4 Testing Vector equality using all function

a<-c(1,2,3,4,5) # Returns elements from 1 to 5
b<-1:5 # Returns elements from 1 to 5
all(a==b) # True when every element is true.
## [1] TRUE

1.5 Testing vector equality using identical function

a<-c(1,2,3,4,5) # Returns elements from 1 to 5
b<-1:5 # Returns elements from 1 to 5
identical(a,b) # The result will not be true because a is numeric datatype and b is integer data type
## [1] FALSE
class(a)
## [1] "numeric"
class(b)
## [1] "integer"

1.6 Vector element names

The elements of a vector can optionally be given names. For example, say we have a 3-element vector showing the weight of each person in the group. We could give name to each person.

x <- c(57,65,49) # Create a vector
names(x) <- c("Ramesh","Suresh","Mahesh") # Providing names to each vector element.
x
## Ramesh Suresh Mahesh 
##     57     65     49

2) Character vectors

Character strings are actually single-element vectors of type character.

2.1 Consider a character vector x

x <- "abc"
length(x) # The length of a is 1 not 3 as any thing between quatation marks are considered as a string.
## [1] 1
class(x) # returns character
## [1] "character"

2.2 Consider a character vector y

y<-c("a","29")
length(y) # Length is 2
## [1] 2
class(y) #Returns character
## [1] "character"

3 String manipulation functions

3.1 The paste function- to concatenate strings

p<-c("abc","de","f") # consider a character vector p
length(p) # Check the length of p
## [1] 3
q<- paste(x) # use paste to concatenate the characters in p
q
## [1] "abc"

3.2 The strsplit function- to split a string

p<-c("abc de f")# consider a character vector p
q<-strsplit(p," ")# use strsplit on vector p and specify space " " as the separator.
q
## [[1]]
## [1] "abc" "de"  "f"