Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Convert Values in Alternate Rows to Negative in Data Table Object in R



To convert values in alternate rows to negative in data.table object in R, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, use vector multiplication with 1 and minus 1 to convert values in alternate rows to negative.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
x<-sample(1:5,30,replace=TRUE)
DT<-data.table(x)
DT

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    x
1:  2
2:  1
3:  3
4:  2
5:  3
6:  3
7:  1
8:  4
9:  3
10: 5
11: 1
12: 5
13: 5
14: 4
15: 2
16: 5
17: 4
18: 5
19: 1
20: 4
21: 3
22: 3
23: 3
24: 1
25: 1
26: 4
27: 3
28: 3
29: 1
30: 3
    x

Convert values in alternate rows to negative

Using vector multiplication with 1 and minus 1 to convert values in alternate rows of column x of data.table object DT to negative −

library(data.table)
x<-sample(1:5,30,replace=TRUE)
DT<-data.table(x)
DT$x<-DT$x*c(1,-1)
DT

Output

     x
1:   2
2:  -1
3:   3
4:  -2
5:   3
6:  -3
7:   1
8:  -4
9:   3
10: -5
11:  1
12: -5
13:  5
14: -4
15:  2
16: -5
17:  4
18: -5
19:  1
20: -4
21:  3
22: -3
23:  3
24: -1
25:  1
26: -4
27:  3
28: -3
29:  1
30: -3
     x
Updated on: 2021-11-15T06:32:19+05:30

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements