How to convert values in alternate rows to negative in matrix in R?


To convert values in alternate rows to negative R matrix, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use vector multiplication with 1 and minus 1 to convert values in alternate rows to negative.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(30,10),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,]  16
[2,]  12
[3,]   8
[4,]  16
[5,]   6
[6,]  11
[7,]   9
[8,]   6
[9,]   8
[10,]  9
[11,] 13
[12,]  4
[13,] 12
[14,] 10
[15,] 10
[16,]  9
[17,] 11
[18,] 11
[19,] 10
[20,]  6
[21,]  8
[22,]  6
[23,]  4
[24,] 10
[25,]  7
[26,] 10
[27,] 12
[28,] 10
[29,]  7
[30,] 11

Convert values in alternate rows to negative

Using vector multiplication with 1 and minus 1 to convert values in alternate rows of column 1 of matrix M to negative −

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

Output

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

Updated on: 15-Nov-2021

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements