
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Divide Matrix Rows in R by Row Median
To divide matrix row values by row median in R, we can follow the below steps −
- First of all, create a matrix.
- Then, use apply function to divide the matrix row values by row median.
Create the matrix
Let's create a matrix as shown below −
M<-matrix(rpois(75,10),ncol=3) M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3] [1,] 11 6 7 [2,] 8 14 6 [3,] 12 11 6 [4,] 11 11 14 [5,] 9 12 9 [6,] 10 8 14 [7,] 7 13 8 [8,] 15 12 13 [9,] 6 18 6 [10,] 7 6 8 [11,] 9 11 11 [12,] 5 7 13 [13,] 15 10 10 [14,] 10 12 6 [15,] 10 14 10 [16,] 11 12 5 [17,] 15 11 11 [18,] 9 8 8 [19,] 14 6 16 [20,] 6 9 6 [21,] 9 10 8 [22,] 11 13 12 [23,] 13 17 8 [24,] 12 11 16 [25,] 11 11 3
Divide the matrix row values by row median
Using apply function to divide the row values of M by row median −
M<-matrix(rpois(75,10),ncol=3) M_new<-t(apply(M,1, function(x) x/median(x))) M_new
Output
[,1] [,2] [,3] [1,] 1.5714286 0.8571429 1.0000000 [2,] 1.0000000 1.7500000 0.7500000 [3,] 1.0909091 1.0000000 0.5454545 [4,] 1.0000000 1.0000000 1.2727273 [5,] 1.0000000 1.3333333 1.0000000 [6,] 1.0000000 0.8000000 1.4000000 [7,] 0.8750000 1.6250000 1.0000000 [8,] 1.1538462 0.9230769 1.0000000 [9,] 1.0000000 3.0000000 1.0000000 [10,] 1.0000000 0.8571429 1.1428571 [11,] 0.8181818 1.0000000 1.0000000 [12,] 0.7142857 1.0000000 1.8571429 [13,] 1.5000000 1.0000000 1.0000000 [14,] 1.0000000 1.2000000 0.6000000 [15,] 1.0000000 1.4000000 1.0000000 [16,] 1.0000000 1.0909091 0.4545455 [17,] 1.3636364 1.0000000 1.0000000 [18,] 1.1250000 1.0000000 1.0000000 [19,] 1.0000000 0.4285714 1.1428571 [20,] 1.0000000 1.5000000 1.0000000 [21,] 1.0000000 1.1111111 0.8888889 [22,] 0.9166667 1.0833333 1.0000000 [23,] 1.0000000 1.3076923 0.6153846 [24,] 1.0000000 0.9166667 1.3333333 [25,] 1.0000000 1.0000000 0.2727273
Advertisements