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


To change the sign of even number rows in a 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 change the sign of even number rows.

Example

Create the data.table object

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

library(data.table)
x<-sample(-5: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:   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

Change the sign of even number rows

Using vector multiplication with 1 and minus 1 to change the sign of even number rows in column x of data.table object DT −

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

Output

     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

Updated on: 09-Nov-2021

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements