
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 Data Frame Row Values in R by Row Median
To divide the data frame row values by row median in R, we can follow the below steps −
- First of all, create a data frame.
- Then, use apply function to divide the data frame row values by row median.
Create the data frame
Let's create a data frame as shown below −
x<-sample(1:100,25) y<-sample(1:100,25) z<-sample(1:100,25) df<-data.frame(x,y,z) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y z 1 8 88 9 2 27 82 20 3 65 63 22 4 89 92 71 5 77 29 35 6 67 76 79 7 100 60 99 8 73 90 21 9 68 85 3 10 50 91 1 11 39 86 2 12 83 84 45 13 20 2 77 14 86 80 8 15 45 72 46 16 14 47 60 17 34 62 49 18 94 44 93 19 42 89 25 20 55 25 4 21 66 97 32 22 85 37 92 23 28 100 19 24 59 51 53 25 93 81 84
Divide the data frame row values by row median
Using apply function to divide the row values of df by row median −
x<-sample(1:100,25) y<-sample(1:100,25) z<-sample(1:100,25) df<-data.frame(x,y,z) df_new<-t(apply(df,1, function(x) x/median(x))) df_new
Output
x y z [1,] 0.8888889 9.7777778 1.00000000 [2,] 1.0000000 3.0370370 0.74074074 [3,] 1.0317460 1.0000000 0.34920635 [4,] 1.0000000 1.0337079 0.79775281 [5,] 2.2000000 0.8285714 1.00000000 [6,] 0.8815789 1.0000000 1.03947368 [7,] 1.0101010 0.6060606 1.00000000 [8,] 1.0000000 1.2328767 0.28767123 [9,] 1.0000000 1.2500000 0.04411765 [10,] 1.0000000 1.8200000 0.02000000 [11,] 1.0000000 2.2051282 0.05128205 [12,] 1.0000000 1.0120482 0.54216867 [13,] 1.0000000 0.1000000 3.85000000 [14,] 1.0750000 1.0000000 0.10000000 [15,] 0.9782609 1.5652174 1.00000000 [16,] 0.2978723 1.0000000 1.27659574 [17,] 0.6938776 1.2653061 1.00000000 [18,] 1.0107527 0.4731183 1.00000000 [19,] 1.0000000 2.1190476 0.59523810 [20,] 2.2000000 1.0000000 0.16000000 [21,] 1.0000000 1.4696970 0.48484848 [22,] 1.0000000 0.4352941 1.08235294 [23,] 1.0000000 3.5714286 0.67857143 [24,] 1.1132075 0.9622642 1.00000000 [25,] 1.1071429 0.9642857 1.00000000
Advertisements