Vectors
Vectors
ANALYTICS - R
PROGRAMMING AND TABLEAU
Module 3
Vector
Packages
• library(tidyverse)
Vector
• is simply a list of items that are of the same
type.
• To combine the list of items to a vector, use
the c() function and separate the items by a
comma.
• Example:
fruits <- c("banana", "apple", "orange")
Cntd
• Vector Length
fruits <- c("banana", "apple", "orange")
length(fruits)
OUTPUT
[1] 3
• Sort a Vector
fruits <- c("banana", "apple", "orange", "mango", "lemon")
numbers <- c(13, 3, 5, 7, 20, 2)
sort(fruits)
sort(numbers)
OUTPUT:
[1] "apple" "banana" "lemon" "mango" "orange"
[1] 2 3 5 7 13 20
Types of vector
There are two types of vectors:
• Atomic vectors, of which there are six types:
logical, integer, double, character, complex, and
raw. Integer and double vectors are collectively
known as numeric vectors.
• Lists, which are sometimes called recursive
vectors because lists can contain other lists.
Difference bw atomic vectors and lists
Atomic vectors are homogeneous, while lists
can be heterogeneous.
The hierarchy of R’s vector types
Vector Data Object Operations:
1. Creation of Vectors:
You can create vectors in R using various methods, including:
Using the ‘c()’ function: This function concatenates elements to form a vector.
Using the ‘:’ operator: This operator creates a sequence of values.
Using functions like ‘seq()’, ‘rep()’, or ‘vector()’ to generate specific types of vectors.
2. Element-wise Operations:
Element-wise operations are performed on vectors by applying an operation to each corresponding pair of
elements. Common element-wise operations include:
Addition: ‘vector1 + vector2’
Subtraction: ‘vector1 - vector2’
Multiplication: ‘vector1 * vector2’
Division: ‘vector1 / vector2’
3. Aggregation Functions:
R provides functions to perform aggregations on vectors, such as:
Sum: ‘sum(vector)’
Mean: ‘mean(vector)’
Minimum: ‘min(vector)’
Maximum: ‘max(vector)’
Median: ‘median(vector)’