How to divide rows in a data.table object by row variance in R?

R ProgrammingServer Side ProgrammingProgramming

<p>To divide the row values by row variance in R&rsquo;s data.table object, we can follow the below steps &minus;</p><ul class="list"><li>First of all, create a data.table object.</li><li>Then, use apply function to divide the data.table object row values by row variance.</li></ul><h2>Create the data.table object</h2><p style="">Let&rsquo;s create a data.table object as shown below &minus;</p><!--<p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p>--><pre class="prettyprint notranslate">library(data.table) x&lt;-sample(1:5,25,replace=TRUE) y&lt;-sample(1:5,25,replace=TRUE) z&lt;-sample(1:5,25,replace=TRUE) DT&lt;-data.table(x,y,z) DT</pre><p>On executing, the above script generates the below output(this output will vary on your system due to randomization) &minus;</p><pre class="result notranslate" style="">&nbsp; &nbsp;x y z 1: 2 2 1 2: 3 4 3 3: 2 5 3 4: 2 4 3 5: 3 5 1 6: 2 4 4 7: 2 2 2 8: 5 2 3 9: 3 3 3 10: 4 3 4 11: 5 5 2 12: 3 4 1 13: 2 3 2 14: 2 5 2 15: 3 5 3 16: 5 3 2 17: 4 1 3 18: 1 5 3 19: 2 1 1 20: 1 5 3 21: 4 3 4 22: 3 1 5 23: 4 3 5 24: 1 1 4 25: 2 3 2 x y z</pre><h2>Divide the data.table object row values by row variance</h2><p style="">Using apply function to divide the row values of DT by row variance &minus;</p><!--<p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p>--><pre class="prettyprint notranslate" style="">library(data.table) x&lt;-sample(1:5,25,replace=TRUE) y&lt;-sample(1:5,25,replace=TRUE) z&lt;-sample(1:5,25,replace=TRUE) DT&lt;-data.table(x,y,z) DT_new&lt;-t(apply(DT,1, function(x) x/var(x))) DT_new</pre><h4>Output</h4><pre class="result notranslate">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;y &nbsp; &nbsp; &nbsp; &nbsp; z [1,] &nbsp;6.0000000 6.0000000 3.0000000 [2,] &nbsp;9.0000000 12.0000000 9.0000000 [3,] &nbsp;0.8571429 2.1428571 1.2857143 [4,] &nbsp;2.0000000 4.0000000 3.0000000 [5,] &nbsp;0.7500000 1.2500000 0.2500000 [6,] &nbsp;1.5000000 3.0000000 3.0000000 [7,] &nbsp;Inf &nbsp; &nbsp; &nbsp; &nbsp; Inf &nbsp; &nbsp; &nbsp; &nbsp;Inf [8,] &nbsp;2.1428571 0.8571429 1.2857143 [9,] &nbsp;Inf &nbsp; &nbsp; &nbsp; &nbsp; Inf &nbsp; &nbsp; &nbsp; &nbsp; Inf [10,] 12.0000000 9.0000000 12.0000000 [11,] 1.6666667 1.6666667 0.6666667 [12,] 1.2857143 1.7142857 0.4285714 [13,] 6.0000000 9.0000000 6.0000000 [14,] 0.6666667 1.6666667 0.6666667 [15,] 2.2500000 3.7500000 2.2500000 [16,] 2.1428571 1.2857143 0.8571429 [17,] 1.7142857 0.4285714 1.2857143 [18,] 0.2500000 1.2500000 0.7500000 [19,] 6.0000000 3.0000000 3.0000000 [20,] 0.2500000 1.2500000 0.7500000 [21,] 12.0000000 9.0000000 12.0000000 [22,] 0.7500000 0.2500000 1.2500000 [23,] 4.0000000 3.0000000 5.0000000 [24,] 0.3333333 0.3333333 1.3333333 [25,] 6.0000000 9.0000000 6.0000000</pre>
raja
Updated on 14-Aug-2021 08:38:04

Advertisements