How to change the sign of even number rows in single column matrix in R?

R ProgrammingServer Side ProgrammingProgramming

To change the sign of even number rows in R matrix, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use vector multiplication with 1 and minus 1 to change the sign of even number rows.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(30,5),ncol=1)
M

Output

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

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

Change the sign of even number rows

Using vector multiplication with 1 and minus 1 to change the sign of even number rows in column 1 of matrix M −

M<-matrix(rpois(30,5),ncol=1)
M[,1]<-M[,1]*c(1,-1)
M

Output

    [,1]
[1,]   4
[2,]  -5
[3,]  10
[4,]  -6
[5,]   4
[6,]  -4
[7,]   4
[8,]  -4
[9,]   1
[10,] -6
[11,]  2
[12,] -4
[13,]  5
[14,] -5
[15,]  2
[16,] -6
[17,]  4
[18,] -7
[19,]  2
[20,] -10
[21,]  3
[22,] -5
[23,]  9
[24,] -4
[25,]  4
[26,] -4
[27,]  5
[28,] -6
[29,]  5
[30,] -6
raja
Updated on 10-Nov-2021 07:06:54

Advertisements