Author: Pooja Kotwani

  • Combining Matrices in R

    Combining Matrices in detail

    Combining matrices involves merging two or more smaller matrices, either by rows or columns, to create a larger matrix. This operation is a fundamental data manipulation technique where the matrices involved must be of compatible dimensions. Matrices can be combined either horizontally or vertically.

    Methods of Combining Matrices in R:
    1. Column-wise combination
    2. Row-wise combination

    1. Column-Wise Combination

    Column binding is performed using the cbind() function in R. It merges two matrices, A(m×n) and B(m×n), column-wise, provided they have the same number of rows.

    Example:

    # R program to combine two matrices column-wise
    
    # Creating the first matrix
    X = matrix(c(2, 4, 6), nrow = 3, ncol = 1)
    
    # Creating the second matrix
    Y = matrix(c(8, 10, 12, 14, 16, 18), nrow = 3, ncol = 2)
    
    # Displaying original matrices
    print(X)
    print(Y)
    
    # Combining matrices
    print(cbind(X, Y))

    Output:

    [,1]
    [1,]    2
    [2,]    4
    [3,]    6
         [,1] [,2]
    [1,]    8   10
    [2,]   12   14
    [3,]   16   18
         [,1] [,2] [,3]
    [1,]    2    8   10
    [2,]    4   12   14
    [3,]    6   16   18

    Here, the columns [8 10][12 14], and [16 18] from matrix Y are appended to the column [2 4 6] of matrix X in order. This does not modify the original matrices.

    Properties:

    • The total number of columns in the resultant matrix equals the sum of columns from the input matrices.
    • Non-Commutative: The order in which matrices are combined matters, meaning cbind(A, B) ≠ cbind(B, A).
    • Associativecbind(cbind(A, B), C) = cbind(A, cbind(B, C)).

    2. Row-Wise Combination

    Row binding is done using the rbind() function in R. It merges two matrices, A_(m×p) and B_(n×p), row-wise, as long as they have the same number of columns.

    Example:

    # R program to combine two matrices row-wise
    
    # Creating the first matrix
    X = matrix(c(1, 3, 5, 7), nrow = 2, ncol = 2)
    
    # Creating the second matrix
    Y = matrix(c(9, 11, 13, 15), nrow = 2, ncol = 2)
    
    # Displaying original matrices
    print(X)
    print(Y)
    
    # Combining matrices
    print(rbind(X, Y))

    Output:

    [,1] [,2]
    [1,]    1    3
    [2,]    5    7
         [,1] [,2]
    [1,]    9   11
    [2,]   13   15
         [,1] [,2]
    [1,]    1    3
    [2,]    5    7
    [3,]    9   11
    [4,]   13   15

    In this case, the rows [9 11] and [13 15] from matrix Y are appended to the rows [1 3] and [5 7] of matrix X in order. The original matrices remain unchanged.

    Properties:

    • The total number of rows in the resultant matrix equals the sum of rows from the input matrices.
    • Non-Commutative: The order in which matrices are merged affects the result, meaning rbind(A, B) ≠ rbind(B, A).
    • Associativerbind(rbind(A, B), C) = rbind(A, rbind(B, C)).

    Complexity Analysis:

    • Time Complexity:
    • Space Complexity: , where is the number of elements in the first matrix and is the number of elements in the second matrix.
  • Algebraic Operations on a Matrix in R

    Algebraic Operations on a Matrix in detail

    In this article, we will explore how to perform algebraic operations on matrices using the R programming language. Let’s begin by understanding what a matrix is.

    What is a Matrix?

    A matrix is a two-dimensional rectangular array of numbers arranged in rows and columns. Rows run horizontally, while columns are vertical. In R, matrices are homogeneous data structures, meaning all elements must be of the same type.

    Algebraic Operations on Matrices

    Algebraic operations include fundamental arithmetic operations like addition, subtraction, multiplication, and division, as well as more advanced matrix operations such as determinant, inverse, eigenvalues, and solving linear equations.

    Operations on a Single Matrix

    R allows element-wise operations on matrices using overloaded arithmetic operators. Let’s look at some examples.

    # Creating a 2x3 matrix
    mat1 <- matrix(c(2, 4, 6, 8, 10, 12), nrow=2, ncol=3, byrow=TRUE)
    cat("Original Matrix:\n")
    print(mat1)
    
    # Adding 2 to each element
    cat("Adding 2 to each element:\n")
    print(mat1 + 2)
    
    # Subtracting 3 from each element
    cat("Subtracting 3 from each element:\n")
    print(mat1 - 3)
    
    # Multiplying each element by 5
    cat("Multiplying each element by 5:\n")
    print(mat1 * 5)
    
    # Squaring each element
    cat("Squaring each element:\n")
    print(mat1 ^ 2)
    Unary Operations

    Unary operations include functions that act on all elements of the matrix, such as finding the maximum, minimum, or sum of elements.

    # Creating a 3x3 matrix
    mat2 <- matrix(c(3, 5, 7, 9, 11, 13, 15, 17, 19), nrow=3, ncol=3, byrow=TRUE)
    cat("Matrix:\n")
    print(mat2)
    
    # Maximum element
    cat("Maximum element:\n")
    print(max(mat2))
    
    # Minimum element
    cat("Minimum element:\n")
    print(min(mat2))
    
    # Sum of all elements
    cat("Sum of all elements:\n")
    print(sum(mat2))
    Unary Operations

    Unary operations include functions that act on all elements of the matrix, such as finding the maximum, minimum, or sum of elements.

    # Creating a 3x3 matrix
    mat2 <- matrix(c(3, 5, 7, 9, 11, 13, 15, 17, 19), nrow=3, ncol=3, byrow=TRUE)
    cat("Matrix:\n")
    print(mat2)
    
    # Maximum element
    cat("Maximum element:\n")
    print(max(mat2))
    
    # Minimum element
    cat("Minimum element:\n")
    print(min(mat2))
    
    # Sum of all elements
    cat("Sum of all elements:\n")
    print(sum(mat2))
    Binary Operations

    Binary operations apply arithmetic operations between two matrices of the same dimensions.

    # Creating two 2x2 matrices
    mat3 <- matrix(c(2, 4, 6, 8), nrow=2, ncol=2, byrow=TRUE)
    mat4 <- matrix(c(1, 3, 5, 7), nrow=2, ncol=2, byrow=TRUE)
    
    cat("Matrix 1:\n")
    print(mat3)
    cat("Matrix 2:\n")
    print(mat4)
    
    # Addition
    cat("Matrix Addition:\n")
    print(mat3 + mat4)
    
    # Subtraction
    cat("Matrix Subtraction:\n")
    print(mat3 - mat4)
    
    # Element-wise multiplication
    cat("Element-wise Multiplication:\n")
    print(mat3 * mat4)
    
    # Matrix multiplication
    cat("Matrix Multiplication:\n")
    print(mat3 %*% mat4)
    Linear Algebraic Operations

    Some fundamental linear algebraic operations include rank, determinant, transpose, and inverse.

    # Importing required library
    library(MASS)
    
    # Creating a 3x3 matrix
    mat5 <- matrix(c(4, 2, 1, 6, 5, 3, 9, 8, 7), nrow=3, ncol=3, byrow=TRUE)
    
    cat("Matrix:\n")
    print(mat5)
    
    # Determinant
    cat("Determinant of the matrix:\n")
    print(det(mat5))
    
    # Transpose
    cat("Transpose of the matrix:\n")
    print(t(mat5))
    
    # Inverse
    cat("Inverse of the matrix:\n")
    print(ginv(mat5))

    Eigenvalues and Eigenvectors

    # Creating a matrix
    mat6 <- matrix(c(1, 4, 2, 3), nrow=2, ncol=2)
    cat("Matrix:\n")
    print(mat6)
    
    # Eigenvalues and eigenvectors
    cat("Eigenvalues and Eigenvectors:\n")
    print(eigen(mat6))
    Solving a Linear Equation
    # Creating matrices
    A <- matrix(c(3, 2, 1, 4), nrow=2, ncol=2)
    B <- matrix(c(7, 10), nrow=2, ncol=1)
    
    cat("Matrix A:\n")
    print(A)
    cat("Matrix B:\n")
    print(B)
    
    # Solving Ax = B
    cat("Solution for Ax = B:\n")
    print(solve(A, B))
  • Operations on Matrices in R

    Operations on Matrices in detail

    Matrices in R consist of values, either real or complex numbers, arranged in a structured format with a fixed number of rows and columns. They are essential for representing data in an organized manner. Elements in a matrix should be enclosed in brackets or parentheses.

    For example, a matrix with 9 elements is shown below:

    [  1  2  3  ]
    [  4  5  6  ]
    [  7  8  9  ]

    This matrix A has 3 rows and 3 columns. Each element can be identified by its row and column index. For instance, a[2,3] = 6.

    The order of a matrix is determined by the number of rows and columns:

    Order = Number of rows × Number of columns

    So, matrix A has an order of 3 × 3.

    Operations on Matrices

    The fundamental matrix operations include Addition, Subtraction, Multiplication, and Division. Both matrices must have the same dimensions for these operations to be performed.

    1. Matrix Addition: The sum of two matrices of the same order results in another matrix where each element is the sum of corresponding elements.

    R Code for Matrix Addition

    # Creating First Matrix
    M1 = matrix(c(2, 4, 6, 8, 10, 12), nrow = 2, ncol = 3)
    
    # Creating Second Matrix
    M2 = matrix(c(1, 3, 5, 7, 9, 11), nrow = 2, ncol = 3)
    
    # Performing Addition
    result = M1 + M2
    
    # Printing Result
    print(result)

    Output:

    [,1] [,2] [,3]
    [1,]    3    7   11
    [2,]    5   11   17

    2. Matrix Subtraction

    Matrix subtraction works similarly, where each element of the second matrix is subtracted from the corresponding element of the first.

    R Code for Matrix Subtraction

    # Creating Matrices
    M1 = matrix(c(5, 10, 15, 20, 25, 30), nrow = 2, ncol = 3)
    M2 = matrix(c(2, 4, 6, 8, 10, 12), nrow = 2, ncol = 3)
    
    # Performing Subtraction
    result = M1 - M2
    
    # Printing Result
    print(result)

    Output:

    [,1] [,2] [,3]
    [1,]    3    6    9
    [2,]   12   15   18

    3. Matrix Multiplication: Matrix multiplication involves multiplying corresponding elements when matrices have the same dimensions.

    R Code for Matrix Multiplication

    # Creating Matrices
    M1 = matrix(c(2, 3, 4, 5, 6, 7), nrow = 2, ncol = 3)
    M2 = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
    
    # Element-wise Multiplication
    result = M1 * M2
    
    # Printing Result
    print(result)

    Output:

    [,1] [,2] [,3]
    [1,]    2    6   12
    [2,]   20   30   42

    4. Matrix Division: Each element of the first matrix is divided by the corresponding element of the second matrix.

    R Code for Matrix Division

    # Creating Matrices
    M1 = matrix(c(10, 20, 30, 40, 50, 60), nrow = 2, ncol = 3)
    M2 = matrix(c(2, 4, 6, 8, 10, 12), nrow = 2, ncol = 3)
    
    # Element-wise Division
    result = M1 / M2
    
    # Printing Result
    print(result)

    Output:

    [,1] [,2] [,3]
    [1,]  5.0  5.0  5.0
    [2,]  5.0  5.0  5.0
    Properties of Matrix Operations

    Matrix Addition Properties:

    1. Commutative: M1 + M2 = M2 + M1
    2. Associative: M1 + (M2 + M3) = (M1 + M2) + M3
    3. Matrices must have the same dimensions.

    Matrix Subtraction Properties:

    1. Non-Commutative: M1 – M2 ≠ M2 – M1
    2. Non-Associative: M1 – (M2 – M3) ≠ (M1 – M2) – M3
    3. Matrices must have the same dimensions.

    Matrix Multiplication Properties:

    1. Commutative: M1 * M2 = M2 * M1
    2. Associative: M1 * (M2 * M3) = (M1 * M2) * M3
    3. Matrices must have the same dimensions.

    Matrix Division Properties:

    1. Non-Commutative: M1 / M2 ≠ M2 / M1
    2. Non-Associative: M1 / (M2 / M3) ≠ (M1 / M2) / M3
    3. Matrices must have the same dimensions.
  • Create Matrix from Vectors

    Matrix from Vectors in detail

    In R, a vector is a basic data structure consisting of homogeneous elements. These elements can have various data types, such as integer, double, character, logical, complex, or raw. The c() function is used to create vectors in R.

    Syntax for creating a vector:

    x <- c(val1, val2, …)

    Vectors can be transformed into matrices in R. Matrices are similar to arrays in other programming languages, like C, and they hold multiple data elements of the same type. You can create matrices using various functions in R that take vectors as input and specify dimensions for the matrix.

    Functions Used to Convert a Vector to a Matrix:
    • matrix()
    • cbind()
    • rbind()
    • array()
    • diag()

    1. Using matrix() Function: The matrix() function is used to create a matrix from a vector. You can specify the number of rows, columns, and whether the matrix should be filled row-wise or column-wise.

    Syntax:

    matrix(data, nrow, ncol, byrow, dimnames)

    Where:

    • data is the vector that contains the elements for the matrix.
    • nrow specifies the number of rows.
    • ncol specifies the number of columns.
    • byrow is a logical value that determines if the matrix should be filled by row (TRUE) or column (FALSE).
    • dimnames specifies the row and column names.

    Example:

    # Defining data in the vector
    x <- c(1:12)
    
    # Defining row and column names
    rows <- c("row_1", "row_2", "row_3")
    cols <- c("col_1", "col_2", "col_3", "col_4")
    
    # Creating matrix
    m <- matrix(x, nrow = 3, byrow = TRUE, dimnames = list(rows, cols))
    
    # Printing the matrix
    print(m)

    Output:

    col_1 col_2 col_3 col_4
    row_1     1     2     3     4
    row_2     5     6     7     8
    row_3     9    10    11    12

    Class of m:

    class(m)

    Output:

    [1] "matrix" "array"

    2. Using cbind() Function: The cbind() function is used to combine vectors by columns. It is important to ensure that the number of rows in each vector is the same to avoid errors.

    Syntax:

    cbind(v1, v2, v3, …, deparse.level)

    Where:

    • v1, v2, v3, … represent vectors, matrices, or data frames.
    • deparse.level specifies the labeling of non-matrix arguments.

    Example:

    # Defining vectors
    v1 <- c(1:5)
    v2 <- c(6:10)
    v3 <- c(11:15)
    
    # Creating matrix by columns
    m <- cbind(v1, v2, v3)
    
    # Printing the matrix
    print(m)

    Output:

    v1 v2 v3
    [1,]  1  6 11
    [2,]  2  7 12
    [3,]  3  8 13
    [4,]  4  9 14
    [5,]  5 10 15

    3. Using rbind() Function: The rbind() function combines vectors by rows. Again, the number of columns in each vector must match.

    Syntax:

    rbind(v1, v2, v3, …, deparse.level)

    Example:

    # Defining vectors
    v1 <- c(1:5)
    v2 <- c(6:10)
    v3 <- c(11:15)
    
    # Creating matrix by rows
    m <- rbind(v1, v2, v3)
    
    # Printing the matrix
    print(m)

    Output:

    [,1] [,2] [,3] [,4] [,5]
    v1    1    2    3    4    5
    v2    6    7    8    9   10
    v3   11   12   13   14   15

    4. Using array() Function: The array() function can also create matrices, but it’s more versatile and can handle multi-dimensional arrays.

    Syntax:

    array(data, dim)

    Where:

    • data is the input vector.
    • dim is a vector specifying the dimensions.

    Example:

    # Defining vectors
    v1 <- c(1:5)
    v2 <- c(6:10)
    v3 <- c(11:15)
    
    # Using the array() function
    m <- array(c(v1, v2, v3), dim = c(5, 3))
    
    # Printing the matrix
    print(m)

    Output:

    [,1] [,2] [,3]
    [1,]    1    6   11
    [2,]    2    7   12
    [3,]    3    8   13
    [4,]    4    9   14
    [5,]    5   10   15

    5. Using diag() Function: The diag() function creates a matrix with the given vector placed on the diagonal.

    Syntax:

    diag(x, nrow, ncol)

    Where:

    • x is the vector that will be placed on the diagonal.
    • nrow specifies the number of rows.
    • ncol specifies the number of columns.

    Example:

    # Defining vectors
    v1 <- c(1:5)
    v2 <- c(6:10)
    v3 <- c(11:15)
    
    # Creating a matrix with vector elements on the diagonal
    m <- diag(c(v1, v2, v3))
    
    # Printing the matrix
    print(m)

    Output:

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
     [1,]    1    0    0    0    0    0    0    0    0     0     0     0     0     0     0
     [2,]    0    2    0    0    0    0    0    0    0     0     0     0     0     0     0
     [3,]    0    0    3    0    0    0    0    0    0     0     0     0     0     0     0
     [4,]    0    0    0    4    0    0    0    0    0     0     0     0     0     0     0
     [5,]    0    0    0    0    5    0    0    0    0     0     0     0     0     0     0
     [6,]    0    0    0    0    0   11    0    0    0     0     0     0     0     0     0
     [7,]    0    0    0    0    0    0   12    0    0     0     0     0     0     0     0
     [8,]    0    0    0    0    0    0    0   13    0     0     0     0     0     0     0
     [9,]    0    0    0    0    0    0    0    0   14     0     0     0     0     0     0
    [10,]    0    0    0    0    0    0    0    0    0    15     0     0     0     0     0
    [11,]    0    0    0    0    0    0    0    0    0     0    21     0     0     0     0
    [12,]    0    0    0    0    0    0    0    0    0     0     0    22     0     0     0
    [13,]    0    0    0    0    0    0    0    0    0     0     0     0    23     0     0
    [14,]    0    0    0    0    0    0    0    0    0     0     0     0     0    24     0
    [15,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0    25

    Class of m:

    class(m)

    Output:

    [1] "matrix" "array"

  • R – Matrices

    R – Matrices in detail

    A matrix is a two-dimensional structure in R that organizes data into rows and columns. Rows extend horizontally, while columns extend vertically. In R, matrices are homogeneous, meaning all elements must be of the same type (e.g., numeric, character, or logical).

    Creating a Matrix in R

    R provides the matrix() function to create matrices. The function requires a set of elements and the number of rows and columns to structure the matrix.

    Note: By default, matrices in R are filled column-wise.

    Syntax:

    matrix(data, nrow, ncol, byrow, dimnames)

    Parameters:

    • data – Values to populate the matrix.
    • nrow – Number of rows.
    • ncol – Number of columns.
    • byrow – If TRUE, fills the matrix row-wise; otherwise, column-wise.
    • dimnames – Assigns names to rows and columns.

    Example:

    # Creating a 3x3 matrix
    M = matrix(
      c(10, 20, 30, 40, 50, 60, 70, 80, 90),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    
    # Naming rows and columns
    rownames(M) = c("X", "Y", "Z")
    colnames(M) = c("A", "B", "C")
    
    cat("The 3x3 matrix:\n")
    print(M)

    Output:

    The 3x3 matrix:
       A  B  C
    X 10 20 30
    Y 40 50 60
    Z 70 80 90
    Creating Special Matrices in R

    R allows generating specific types of matrices using different arguments within the matrix() function.

    1. Constant Matrix: A matrix where all elements are filled with a single constant value.

    Syntax:

    # Creating a 4x4 matrix filled with 7
    print(matrix(7, 4, 4))

    Output:

    [,1] [,2] [,3] [,4]
    [1,]    7    7    7    7
    [2,]    7    7    7    7
    [3,]    7    7    7    7
    [4,]    7    7    7    7

    2. Diagonal Matrix: A diagonal matrix has nonzero values only on its main diagonal, with zeros elsewhere.

    Syntax:

    diag(values, m, n)

    Example:

    # Creating a 3x3 diagonal matrix
    print(diag(c(2, 4, 6), 3, 3))

    Output:

    [,1] [,2] [,3]
    [1,]    2    0    0
    [2,]    0    4    0
    [3,]    0    0    6

    3. Identity Matrix: An identity matrix has ones along the diagonal and zeros elsewhere.

    Syntax:

    diag(values, m, n)

    Example:

    # Creating a 4x4 identity matrix
    print(diag(1, 4, 4))

    Output:

    [,1] [,2] [,3] [,4]
    [1,]    1    0    0    0
    [2,]    0    1    0    0
    [3,]    0    0    1    0
    [4,]    0    0    0    1
    Matrix Properties

    Matrix properties provide useful insights into the structure of a matrix, such as its dimensions, number of rows, and total number of elements.

    Example:

    # Creating a 2x4 matrix
    M = matrix(c(3, 6, 9, 12, 15, 18, 21, 24), nrow = 2, ncol = 4, byrow = TRUE)
    
    cat("The matrix:\n")
    print(M)
    
    cat("Dimensions of the matrix:\n")
    print(dim(M))
    
    cat("Number of rows:\n")
    print(nrow(M))
    
    cat("Number of columns:\n")
    print(ncol(M))
    
    cat("Total elements in the matrix:\n")
    print(length(M))

    Output:

    The matrix:
         [,1] [,2] [,3] [,4]
    [1,]    3    6    9   12
    [2,]   15   18   21   24
    Dimensions of the matrix:
    [1] 2 4
    Number of rows:
    [1] 2
    Number of columns:
    [1] 4
    Total elements in the matrix:
    [1] 8
    Accessing Elements in R-Matrix

    In R, you can access elements of a matrix using indexing, where the row index appears before the comma and the column index comes after. Let’s explore how to access rows, columns, and individual elements in a matrix.

    Accessing Rows:

    # Create a 3x3 matrix
    matrix_A <- matrix(
      c(1, 2, 3, 4, 5, 6, 7, 8, 9),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    
    cat("The 3x3 matrix:\n")
    print(matrix_A)
    
    # Accessing the first two rows
    cat("Accessing the first two rows:\n")
    print(matrix_A[1:2, ])

    Output:

    The 3x3 matrix:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8    9
    
    Accessing the first two rows:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6

    Accessing Columns:

    # Accessing the first two columns
    cat("Accessing the first two columns:\n")
    print(matrix_A[, 1:2])

    Output:

    Accessing the first two columns:
         [,1] [,2]
    [1,]    1    2
    [2,]    4    5
    [3,]    7    8

    Accessing Specific Elements:

    # Accessing individual elements
    cat("Accessing element in the first row and second column:\n")
    print(matrix_A[1, 2])
    
    cat("Accessing element in the second row and third column:\n")
    print(matrix_A[2, 3])

    Output:

    Accessing element in the first row and second column:
    [1] 2
    
    Accessing element in the second row and third column:
    [1] 6

    Accessing Submatrices:

    # Accessing a submatrix (first two rows and first two columns)
    cat("Accessing a submatrix (first two rows and columns):\n")
    print(matrix_A[1:2, 1:2])

    Output:

    Accessing a submatrix (first two rows and columns):
         [,1] [,2]
    [1,]    1    2
    [2,]    4    5
    Modifying Elements in an R-Matrix

    You can change the values of elements directly by assigning a new value.

    Modifying an Element:

    # Modifying the element in the third row and third column
    matrix_A[3, 3] <- 30
    
    cat("After modifying the element:\n")
    print(matrix_A)

    Output:

    After modifying the element:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8   30
    Concatenating Matrices in R

    You can concatenate matrices either by adding rows or columns using the rbind() and cbind() functions.

    Concatenating a Row:

    # Create a 3x3 matrix
    matrix_A <- matrix(
      c(1, 2, 3, 4, 5, 6, 7, 8, 9),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    
    # Create a 1x3 matrix to append as a row
    matrix_B <- matrix(c(10, 11, 12), nrow = 1, ncol = 3)
    
    cat("The 3x3 matrix before row concatenation:\n")
    print(matrix_A)
    
    cat("The 1x3 matrix to add as a row:\n")
    print(matrix_B)
    
    # Concatenating a new row
    matrix_C <- rbind(matrix_A, matrix_B)
    
    cat("After concatenating the row:\n")
    print(matrix_C)

    Output:

    The 3x3 matrix before row concatenation:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8    9
    
    The 1x3 matrix to add as a row:
         [,1] [,2] [,3]
    [1,]   10   11   12
    
    After concatenating the row:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8    9
    [4,]   10   11   12

    Concatenating a Column:

    # Create a 3x3 matrix
    matrix_A <- matrix(
      c(1, 2, 3, 4, 5, 6, 7, 8, 9),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    
    # Create a 3x1 matrix to append as a column
    matrix_B <- matrix(c(10, 11, 12), nrow = 3, ncol = 1)
    
    cat("The 3x3 matrix before column concatenation:\n")
    print(matrix_A)
    
    cat("The 3x1 matrix to add as a column:\n")
    print(matrix_B)
    
    # Concatenating a new column
    matrix_C <- cbind(matrix_A, matrix_B)
    
    cat("After concatenating the column:\n")
    print(matrix_C)

    Output:

    The 3x3 matrix before column concatenation:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8    9
    
    The 3x1 matrix to add as a column:
         [,1]
    [1,]   10
    [2,]   11
    [3,]   12
    
    After concatenating the column:
         [,1] [,2] [,3] [,4]
    [1,]    1    2    3   10
    [2,]    4    5    6   11
    [3,]    7    8    9   12
    Deleting Rows and Columns in R-Matrix

    To delete rows or columns, you can use negative indexing.

    Deleting a Row:

    # Deleting the second row
    matrix_A <- matrix_A[-2, ]
    
    cat("After deleting the second row:\n")
    print(matrix_A)

    Output:

    After deleting the second row:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    7    8    9

    Deleting a Column:

    # Deleting the second column
    matrix_A <- matrix_A[, -2]
    
    cat("After deleting the second column:\n")
    print(matrix_A)

    Output:

    After deleting the second column:
         [,1] [,3]
    [1,]    1    3
    [2,]    7    9

  • Extracting Substrings from a Character Vector in R Programming – substring() Function

    substring() Function in detail

    The substring() function in R programming is used to extract substrings from a character vector. It allows you to extract specific substrings or characters from the provided string easily.

    Syntax:

    substring(text, first, last)

    Parameters:

    • text: Character vector.
    • first: Integer, specifying the starting position of the substring.
    • last: Integer, specifying the ending position of the substring.

    Example 1: Extracting values with substring() function in R

    # R program to demonstrate
    # the substring() function
    
    # Extracting substrings
    substring("Hello", 2, 4)
    substring("World", 1, 3)
    substring("R", 1, 1)
    substring("data", 4, 4)

    Output:

    [1] "ell"
    [1] "Wor"
    [1] "R"
    [1] "a"

    Example 2: Using substring() on a character vector

    # R program to demonstrate
    # substring function on a vector
    
    # Initializing a character vector
    vec <- c("Code", "data", "Analysis")
    
    # Extracting substrings
    substring(vec, 2, 3)
    substring(vec, 1, 4)
    substring(vec, 3, 3)

    Output:

    [1] "od" "at" "na"
    [1] "Code" "data" "Anal"
    [1] "d" "t" "a"

    Example 3: Replacing substrings in R using substring()

    # R program to demonstrate
    # substring replacement
    
    # Initializing a character vector
    vec <- c("Code", "data", "string")
    
    # Replacing substrings
    substring(vec, 2, 3) <- c("X")
    print(vec)

    Output:

    [1] "CXde"  "dXta"  "sXring"
  • Convert elements of a Vector to Strings in R Language – toString() Function

    toString() Function in detail

    The toString() function in R is used to generate a single character string that describes an R object.

    Syntax:

    toString(x, width = NULL)

    Parameters:

    • x: An R object (e.g., vector, matrix, etc.)
    • width: Suggestion for the maximum field width. Values of NULL or 0 imply no maximum. The minimum accepted value is 6, and smaller values are treated as 6.

    toString() Function in R Language Examples

    Example 1: Basic Example of toString() Function

    # R program to illustrate
    # toString function
    
    # Initializing a numeric vector
    vec <- c(1, 2, 3, 4, 5)
    
    # Calling the toString() function
    result <- toString(vec)
    print(result)

    Output:

    [1] "1, 2, 3, 4, 5"

    Example 2: Formatting with toString() Function

    # R program to illustrate
    # toString function with width parameter
    
    # Initializing a character vector
    chars <- c("Apple", "Banana", "Cherry")
    
    # Applying the toString() function with different widths
    print(toString(chars, width = 6))
    print(toString(chars, width = 10))
    print(toString(chars, width = 15))

    Output:

    [1] "App..."
    [1] "Apple, ..."
    [1] "Apple, Ba..."

    Example 3: Convert Matrix to String

    # Matrix with 2 rows and 3 columns
    mat <- matrix(c(10, 20, 30, 40, 50, 60), nrow = 2, ncol = 3)
    
    # Printing the matrix
    print("Matrix:")
    print(mat)
    
    # Converting matrix to string
    mat_str <- toString(mat)
    
    # Printing the string representation
    print("Matrix as String:")
    print(mat_str)

    Output:

    [1] "Matrix:"
         [,1] [,2] [,3]
    [1,]   10   30   50
    [2,]   20   40   60
    [1] "Matrix as String:"
    [1] "10, 20, 30, 40, 50, 60"
  • Sorting of a Vector in R Programming – sort() Function

    sort() Function in detail

    In R, the sort() function is used to arrange the elements of a vector in either ascending or descending order. It returns a sorted version of the input vector and can also handle missing values (NA).

    Syntax:

    sort(x, decreasing, na.last)

    Parameters:

    • x: The vector to be sorted.
    • decreasing: A Boolean value (TRUE or FALSE). If TRUE, sorts the vector in descending order.
    • na.last: A Boolean value. If TRUE, places NA values at the end; if FALSE, places them at the beginning.

    Example 1: Sorting Numeric Vectors

    # Creating a numeric vector
    numbers <- c(10, -3, 5, 7, 2, NA, -8, 15)
    
    # Sort in ascending order
    sorted_numbers <- sort(numbers)
    print(sorted_numbers)

    Output:

    [1] -8 -3  2  5  7 10 15

    Example 2: Sorting with Descending Order and NA Handling

    # Creating a numeric vector
    values <- c(20, -7, 4, NA, 0, 12, -15)
    
    # Sort in descending order
    sorted_desc <- sort(values, decreasing = TRUE)
    print(sorted_desc)
    
    # Sort with NA values at the end
    sorted_na_last <- sort(values, na.last = TRUE)
    print(sorted_na_last)

    Output:

    [1] 20 12  4  0 -7 -15
    [1] -15  -7   0   4  12  20   NA

    Example 3: Sorting Character Vectors

    # Creating a character vector
    cities <- c("Delhi", "Mumbai", "Chennai", "Kolkata")
    
    # Sort alphabetically
    sorted_cities <- sort(cities)
    print(sorted_cities)

    Output:

    [1] "Chennai" "Delhi" "Kolkata" "Mumbai"
  • Replace the Elements of a Vector in R Programming – replace() Function

    replace() Function in detail

    The replace() function in R is used to replace specific values in a given vector at specified indices with new values.

    Syntax:

    replace(x, list, values)

    Parameters:

    • x: The input vector.
    • list: Indices where values need to be replaced.
    • values: New values that will replace the existing ones at the specified indices.

    Example 1:

    # R program to demonstrate
    # replace function
    
    # Initializing a vector
    data <- c("Apple", "Banana", "Cherry")
    
    # Display the original vector
    data
    
    # Replace the element at index 2 with "Blueberry"
    updated_data <- replace(data, 2, "Blueberry")
    
    # Display the updated vector
    updated_data

    Output:

    [1] "Apple"   "Banana"   "Cherry"
    [1] "Apple"   "Blueberry"   "Cherry"

    Example 2:

    # R program to demonstrate
    # replace function
    
    # Initializing a vector
    data <- c("Red", "Green", "Blue")
    
    # Display the original vector
    data
    
    # Replace the element at index 1 with "Yellow"
    # and the element at index 3 with "Orange"
    updated_data <- replace(data, c(1, 3), c("Yellow", "Orange"))
    
    # Display the updated vector
    updated_data

    Output:

    [1] "Red"   "Green"   "Blue"
    [1] "Yellow"   "Green"   "Orange"
  • Formatting Numbers and Strings in R Programming – format() Function

    Formatting Numbers and Strings in detail

    The format() function in R is a versatile tool that allows us to convert various objects, such as character strings, date/time data, and numeric values, into specific representations. By providing a wide range of formatting options, the function helps us control the appearance of the output.

    Using the format() function, we can customize numerical formatting by specifying parameters such as the number of decimal places (nsmall), the thousands separator (big.mark), the decimal mark (decimal.mark), and other relevant settings. Similarly, it enables the formatting of strings to follow a specific locale or meet particular presentation requirements.

    Syntax:

    format(x, digits, nsmall, scientific, width, justify = c("left", "right", "center", "none"))

    Parameters:

    • x: Input vector.
    • digits: Total number of digits to be displayed.
    • nsmall: Minimum number of digits to the right of the decimal point.
    • scientific: Set to TRUE to use scientific notation.
    • width: Minimum width of the output, with blank spaces padded at the beginning.
    • justify: Align the string output to the left, right, or center.
    String Formatting in R

    Example: String Placement with format()

    # Align string to the left
    output1 <- format("Data", width = 10, justify = "l")
    
    # Align string to the center
    output2 <- format("Data", width = 10, justify = "c")
    
    # Align string to the right
    output3 <- format("Data", width = 10, justify = "r")
    
    # Displaying the results
    print(output1)
    print(output2)
    print(output3)

    Output:

    [1] "Data      "
    [1] "   Data   "
    [1] "      Data"
    Number Formatting in R

    Example 1: Formatting Numbers with format()

    # Illustrating the format function
    
    # Rounding off numbers to specific digits
    num1 <- format(15.6789012, digits = 5)
    num2 <- format(15.6789012, digits = 7)
    print(num1)
    print(num2)
    
    # Specifying minimum digits after the decimal
    num3 <- format(15.6789012, nsmall = 3)
    num4 <- format(15.6789012, nsmall = 8)
    print(num3)
    print(num4)

    Output:

    [1] "15.679"
    [1] "15.67890"
    [1] "15.679"
    [1] "15.67890120"

    Example 2: Scientific Notation and String Representation

    # Convert numbers to strings
    str1 <- format(6789)
    str2 <- format(45.6789)
    print(str1)
    print(str2)
    
    # Displaying numbers in scientific notation
    sci1 <- format(45.6789, scientific = TRUE)
    sci2 <- format(45.6789, scientific = FALSE)
    print(sci1)
    print(sci2)

    Output:

    [1] "6789"
    [1] "45.6789"
    [1] "4.56789e+01"
    [1] "45.6789"
    Date and Time Formatting in R

    The format() function can also handle date and time objects, allowing custom string representations to be created.

    Example 1: Current Date and Time

    # Getting current date and time
    current_time <- Sys.time()
    
    # Formatting date-time in "YYYY-MM-DD HH:MM:SS" format
    formatted_time <- format(current_time, format = "%Y-%m-%d %H:%M:%S")
    print(formatted_time)

    Output:

    [1] "2025-01-28 15:45:00"

    Example 2: Date Formatting with Month Name

    # Formatting date with the month's name
    specific_date <- as.Date("2024-11-15")
    formatted_date <- format(specific_date, format = "%B %d, %Y")
    print(formatted_date)

    Output:

    [1] "November 15, 2024"
    • %Y: Year with century (e.g., 2024).
    • %B: Full month name (e.g., November).
    • %d: Day of the month (e.g., 15).