How to change the sign of even number rows in an R data frame column?


To change the sign of even number rows in an R data frame column, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use vector multiplication with 1 and minus 1 to change the sign of even number rows.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rnorm(30)
df<-data.frame(x)
df

Output

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

        x
1  -1.64332327
2  -0.24164407
3  -0.42255909
4   1.73395741
5   0.58392895
6  -1.05693098
7  -0.07579629
8  -1.07794384
9   0.97493467
10 -0.10139958
11  1.03841948
12  0.73837018
13  0.09637912
14 -1.17199796
15 -0.45228897
16 -1.95418740
17  1.60093072
18  0.22397640
19  1.29593124
20 -0.28409879
21 -0.76706673
22 -0.32596245
23 -0.20770367
24 -0.42317987
25  1.17333189
26 -0.44673231
27  0.34579388
28  1.93104978
29  1.18022735
30  1.47573451

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 frame df −

x<-rnorm(30)
df<-data.frame(x)
df$x<-df$x*c(1,-1)
df

Output

       x
1  -1.64332327
2   0.24164407
3  -0.42255909
4  -1.73395741
5   0.58392895
6   1.05693098
7  -0.07579629
8   1.07794384
9   0.97493467
10  0.10139958
11  1.03841948
12 -0.73837018
13  0.09637912
14  1.17199796
15 -0.45228897
16  1.95418740
17  1.60093072
18 -0.22397640
19  1.29593124
20  0.28409879
21 -0.76706673
22  0.32596245
23 -0.20770367
24  0.42317987
25  1.17333189
26  0.44673231
27  0.34579388
28 -1.93104978
29  1.18022735
30 -1.47573451

Updated on: 12-Nov-2021

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements