Changing row and column values of a Matrix in R Language – sweep() function
sweep() function in R Language is used to apply the operation “+ or -” to the row or column in data matrix.
It is used to sweep the values from the data-framework.
Syntax:
sweep(x, MARGIN, STATS, FUN)
Parameters:
x: Typically a matrix.
MARGIN: MARGIN = 1 means row; MARGIN = 2 means column.
STATS: the value that should be added or subtracted
FUN: The operation that has to be done (e.g. + or -)
Example 1: Sweep Matrix
Python3
# R program to illustrate# sweep matrix# Create example matrixdata <- matrix(0, nrow = 6, ncol = 4) # Apply sweep in Rdata_ex1 <- sweep(x = data, MARGIN = 1, STATS = 5, FUN = "+") # Print example 1print(data_ex1) |
Output:
[,1] [,2] [,3] [,4] [1,] 5 5 5 5 [2,] 5 5 5 5 [3,] 5 5 5 5 [4,] 5 5 5 5 [5,] 5 5 5 5 [6,] 5 5 5 5
Here in the above code, the value of the matrix was 0, which was then swept by the sweep() function and the new value of the matrix became 5.
Example 2: Using sweep() with stats
Python3
# R program to illustrate# sweep function with stats# Create example matrixdata <- matrix(0, nrow = 6, ncol = 4) # Sweep with Complex STATSdata_ex2 <- sweep(x = data, MARGIN = 1, STATS = c(1, 2, 3, 4, 5, 6), FUN = "+")# Print example 2print(data_ex2) |
Output:
[,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 2 2 2 2 [3,] 3 3 3 3 [4,] 4 4 4 4 [5,] 5 5 5 5 [6,] 6 6 6 6
Here in the above example, we have used the sweep() function along with the stats.


