How to change the sign of even number rows in column of a data.table object in R?

R ProgrammingServer Side ProgrammingProgramming

<p>To change the sign of even number rows in a data.table object in R, we can follow the below steps &minus;</p><ul class="list"><li><p>First of all, create a data.table object.</p></li><li><p>Then, use vector multiplication with 1 and minus 1 to change the sign of even number rows.</p></li></ul><h2>Example</h2><h4>Create the data.table object</h4><p>Let&rsquo;s create a data.table object as shown below &minus;</p><pre class="just-code notranslate language-rscript" data-lang="rscript">library(data.table) x&lt;-sample(-5:5,30,replace=TRUE) DT&lt;-data.table(x) DT</pre><h2>Output</h2><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"> x 1: 2 2: 3 3: 5 4: 2 5: 5 6: -5 7: 2 8: 3 9: 0 10: 3 11: 3 12: -3 13: -1 14: -4 15: 5 16: 5 17: -1 18: -4 19: -5 20: -1 21: 4 22: 5 23: 2 24: 0 25: -3 26: 0 27: -2 28: 1 29: 4 30: -1 x</pre><p><strong>Change the sign of even number rows</strong></p><p>Using vector multiplication with 1 and minus 1 to change the sign of even number rows in column x of data.table object DT &minus;</p><pre class="just-code notranslate language-rscript" data-lang="rscript">library(data.table) x&lt;-sample(-5:5,30,replace=TRUE) DT&lt;-data.table(x) DT$x&lt;-DT$x*c(1,-1) DT</pre><h2>Output</h2><pre class="result notranslate"> x 1: 2 2: -3 3: 5 4: -2 5: 5 6: 5 7: 2 8: -3 9: 0 10: -3 11: 3 12: 3 13: -1 14: 4 15: 5 16: -5 17: -1 18: 4 19: -5 20: 1 21: 4 22: -5 23: 2 24: 0 25: -3 26: 0 27: -2 28: -1 29: 4 30: 1 x</pre>
raja
Updated on 09-Nov-2021 06:10:11

Advertisements