Skip to content
Related Articles

Related Articles

Changing row and column values of a Matrix in R Language – sweep() function

View Discussion
Improve Article
Save Article
  • Last Updated : 23 Dec, 2021
View Discussion
Improve Article
Save Article

In this article, we will learn changing row and column values of a Matrix in R Programming Language.

R – 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  

R




# R program to illustrate
# sweep matrix
 
# Create example matrix
data <- matrix(0, nrow = 6, ncol = 4)
 
# Apply sweep in R
data_ex1 <- sweep(x = data, MARGIN = 1,
                  STATS = 5, FUN = "+")
 
# Print example 1
print(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  

R




# R program to illustrate
# sweep function with stats
 
# Create example matrix
data <- matrix(0, nrow = 6, ncol = 4)
 
# Sweep with Complex STATS
data_ex2 <- sweep(x = data, MARGIN = 1,
                STATS = c(1, 2, 3, 4, 5, 6),
                  FUN = "+")
 
# Print example 2
print(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. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!