How to combine two rows in R matrix by addition?

R ProgrammingServer Side ProgrammingProgramming

To combine two rows in R matrix by addition, we can follow the below steps −

  • First of all, create a matrix.

  • Then, using plus sign (+) to add two rows and store the addition in one of the rows.

  • After that, remove the row that is not required by subsetting with single square brackets.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(sample(1:5,100,replace=TRUE),ncol=4)
M

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     [,1] [,2] [,3] [,4]
[1,]  4    4    2    1
[2,]  5    4    4    4
[3,]  1    1    5    3
[4,]  1    4    4    4
[5,]  5    1    1    3
[6,]  3    1    2    1
[7,]  4    4    5    2
[8,]  3    4    2    1
[9,]  2    2    4    4
[10,] 4    1    1    2
[11,] 5    3    1    2
[12,] 3    1    2    4
[13,] 3    3    2    3
[14,] 3    3    1    1
[15,] 5    5    5    5
[16,] 4    1    2    5
[17,] 4    2    5    1
[18,] 3    4    1    5
[19,] 5    3    4    4
[20,] 2    5    1    1
[21,] 5    3    5    5
[22,] 2    4    2    3
[23,] 5    5    2    5
[24,] 3    5    4    1
[25,] 4    1    2    5

Add two rows

Using plus sign to add row 1 and row 2 then storing the sum in row 1 −

M<-matrix(sample(1:5,100,replace=TRUE),ncol=4)
M[1,]<-M[1,]+M[2,]
M

Output

     [,1] [,2] [,3] [,4]
[1,]  9    8    6    5
[2,]  5    4    4    4
[3,]  1    1    5    3
[4,]  1    4    4    4
[5,]  5    1    1    3
[6,]  3    1    2    1
[7,]  4    4    5    2
[8,]  3    4    2    1
[9,]  2    2    4    4
[10,] 4    1    1    2
[11,] 5    3    1    2
[12,] 3    1    2    4
[13,] 3    3    2    3
[14,] 3    3    1    1
[15,] 5    5    5    5
[16,] 4    1    2    5
[17,] 4    2    5    1
[18,] 3    4    1    5
[19,] 5    3    4    4
[20,] 2    5    1    1
[21,] 5    3    5    5
[22,] 2    4    2    3
[23,] 5    5    2    5
[24,] 3    5    4    1
[25,] 4    1    2    5

Remove the row which is not required

Using single square subsetting to remove 2nd row from matrix M −

M<-matrix(sample(1:5,100,replace=TRUE),ncol=4)
M[1,]<-M[1,]+M[2,]
M[-2,]

Output

     [,1] [,2] [,3] [,4]
[1,]  9    8    6    5
[2,]  1    1    5    3
[3,]  1    4    4    4
[4,]  5    1    1    3
[5,]  3    1    2    1
[6,]  4    4    5    2
[7,]  3    4    2    1
[8,]  2    2    4    4
[9,]  4    1    1    2
[10,] 5    3    1    2
[11,] 3    1    2    4
[12,] 3    3    2    3
[13,] 3    3    1    1
[14,] 5    5    5    5
[15,] 4    1    2    5
[16,] 4    2    5    1
[17,] 3    4    1    5
[18,] 5    3    4    4
[19,] 2    5    1    1
[20,] 5    3    5    5
[21,] 2    4    2    3
[22,] 5    5    2    5
[23,] 3    5    4    1
[24,] 4    1    2    5
raja
Updated on 08-Nov-2021 10:59:26

Advertisements