How to convert values in alternate rows to negative in R data frame column?


To convert values in alternate rows to negative in 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 convert values in alternate rows to negative.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-sample(1:5,30,replace=TRUE)
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  5
2  2
3  5
4  4
5  5
6  2
7  1
8  5
9  1
10 1
11 3
12 5
13 4
14 5
15 3
16 1
17 4
18 2
19 4
20 1
21 4
22 4
23 5
24 4
25 1
26 1
27 5
28 5
29 4
30 4

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

x<-sample(1:5,30,replace=TRUE)
df<-data.frame(x)
df$x<-df$x*c(1,-1)
df

Output

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

Updated on: 12-Nov-2021

625 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements