![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to change the sign of even number rows in single column matrix in R?
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
Advertisements