R Programming Notes
R Programming Notes
Vectors
Vectors are a fundamental data structure in R used to store sequences of elements that are
all of the same type. They are essential for data manipulation and statistical analysis.
Types of Vectors in R
4. Integer Vector: A special type of numeric vector where all elements are integers.
5. Complex Vector: Contains complex numbers with real and imaginary parts.
Vectors can be created using the c() function, which combines or concatenates elements
into a vector.
1. Numeric Vector
c means concatenate
2. Character Vector
3. Logical Vector
4. Integer Vector
5. Complex Vector
print("Numeric Vector:")
print("Character Vector:")
print("Logical Vector:")
print("Integer Vector:")
print("Complex Vector:")
Vector Operations
Summary
• Vectors are the simplest data structures in R and can only hold elements of the
same type.
• Creation is done using the c() function, and operations on vectors apply to each
element.
1. Arithmetic Operations
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Exponentiation (^)
Example:
Copy code
# Element-wise addition
# Element-wise subtraction
# Element-wise multiplication
# Element-wise division
# Element-wise exponentiation
result_exp <- vec1 ^ vec2 # Outputs: [1] 2^1 4^3 6^5 -> [1] 2 64 7776
2. Relational Operations
• Equal to (==)
Example:
Copy code
result_gt <- vec1 > vec2 # Outputs: [1] TRUE FALSE FALSE
# Equal to comparison
3. Logical Operations
These operations work with logical vectors and return logical results:
• AND (&)
• OR (|)
• NOT (!)
Example:
Copy code
# Logical AND
result_and <- vec1 & vec2 # Outputs: [1] FALSE FALSE TRUE
# Logical OR
# Logical NOT
4. Vector Recycling
If two vectors of different lengths are used in an operation, R recycles the shorter
vector to match the length of the longer one.
Example:
Copy code
Example:
Copy code
# Conditional access
Example:
Copy code
# Sum of elements
# Mean of elements
# Maximum element
Summary
• Recycling allows for operations on vectors of different lengths but may need
attention to avoid unexpected results.
• Element access and functions like sum(), mean(), max(), and min() are useful for
vector manipulation and analysis.
4o
• Repeating a Vector:
rep2 <- rep(c(1, 2, 3), times = 2) # Repeats the vector (1, 2, 3) two times
print(rep2) # Outputs: [1] 1 2 3 1 2 3
• Repeating Each Element:
rep3 <- rep(c(1, 2, 3), each = 3) # Repeats each element of the vector three
times
print(rep3) # Outputs: [1] 1 1 1 2 2 2 3 3 3
3. Sorting
Sorting is used to arrange the elements of a vector in ascending or descending
order. The sort() function is commonly used for this purpose.
Examples:
• Ascending Order:
vec <- c(10, 3, 8, 1, 5)
sorted_vec <- sort(vec) # Sorts in ascending order by default
print(sorted_vec) # Outputs: [1] 1 3 5 8 10
• Descending Order:
sorted_vec_desc <- sort(vec, decreasing = TRUE) # Sorts in descending order
print(sorted_vec_desc) # Outputs: [1] 10 8 5 3 1
4. Lengths
The length() function is used to determine the number of elements in a vector
or list.
Examples:
Matrices
# [,1] [,2]
# [1,] 5 21
# [2,] 12 32
• Transposing a Matrix:
5. Combining Matrices
You can combine matrices by rows or columns using rbind() and cbind().
Example:
mat1 <- matrix(1:4, nrow = 2)
mat2 <- matrix(5:8, nrow = 2)
combined_row <- rbind(mat1, mat2)
print(combined_row)
# Outputs:
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
# [3,] 5 7
# [4,] 6 8
Summary
ARRAY
Arrays in R are multi-dimensional data structures that can hold data of the
same type (usually numeric or character). Unlike matrices, which are limited
to two dimensions, arrays can have more than two dimensions, making them
suitable for more complex data structures.
1. Creating Arrays
You can create arrays in R using the array() function, specifying the data and
dimensions.
Syntax:
array(c(rows,columns,layers).
array(data, dim = c(dim1, dim2, dim3, ...))
• data: The elements to populate the array.
• dim: A vector specifying the number of elements in each dimension.
Example:
arr <- array(1:12, dim = c(3, 4))
print(arr)
# Outputs a 3x4 matrix:
#,,2
# [,1] [,2] [,3] [,4]
# [1,] 13 16 19 22
# [2,] 14 17 20 23
# [3,] 15 18 21 24
You can access elements of an array using indices for each dimension.
Example:
• Accessing a Single Element:
elem <- arr_3d[2, 3, 1] # Accesses the element at the 2nd row, 3rd column,
1st matrix
print(elem) # Outputs: 8
• Accessing an Entire Row or Column:
row_extract <- arr_3d[1, , 2] # Extracts the 1st row from the 2nd matrix
print(row_extract) # Outputs: [1] 13 16 19 22
col_extract <- arr_3d[, 4, 1] # Extracts the 4th column from the 1st matrix
print(col_extract) # Outputs: [1] 10 11 12
• Accessing an Entire Matrix:
matrix_extract <- arr_3d[, , 1] # Extracts the 1st matrix
print(matrix_extract)
# Outputs:
# [,1] [,2] [,3] [,4]
# [1,] 1 4 7 10
# [2,] 2 5 8 11
# [3,] 3 6 9 12
3. Modifying Elements
You can modify elements in an array by assigning new values to specific
positions.
Example:
arr_3d[2, 2, 1] <- 99 # Modifies the element at the 2nd row, 2nd column, 1st
matrix
print(arr_3d[2, , 1]) # Outputs the modified 2nd row of the 1st matrix: [1] 2 99 8
11
4. Array Operations
Arrays support arithmetic operations, which are performed element-wise.
Examples:
• Addition:
arr1 <- array(1:6, dim = c(2, 3))
arr2 <- array(7:12, dim = c(2, 3))
arr_sum <- arr1 + arr2
print(arr_sum)
# Outputs:
# [,1] [,2] [,3]
# [1,] 8 12 16
# [2,] 10 14 18
• Multiplication:
arr_mult <- arr1 * arr2
print(arr_mult)
# Outputs:
# [,1] [,2] [,3]
# [1,] 7 27 55
# [2,] 16 40 72
5. Checking Array Properties
Arrays have certain properties that you can check using various functions:
• dim(): Returns the dimensions of the array.
• length(): Returns the total number of elements in the array.
• dimnames(): Assigns or retrieves names for the dimensions.
Examples: