How to convert negative values in an R data frame to positive values?


Sometimes we need to use absolute values but few values in the data set are negative, therefore, we must convert them to positive. This can be done by using abs function. For example, if we have a data frame df with many columns and each of them having some negative values then those values can be converted to positive values by just using abs(df).

Example

Consider the below data frame −

 Live Demo

set.seed(41)
x1<-sample(-1:1,20,replace=TRUE)
x2<-sample(-5:1,20,replace=TRUE)
df1<-data.frame(x1,x2)
df1

Output

  x1 x2
1  1 -2
2 -1 -4
3  0  1
4  0  0
5 -1 -2
6  0   0
7  0  -4
8  0  -4
9   0 -2
10  1 -2
11  0 -1
12  1 -3
13 -1 -5
14  -1 0
15  0 -3
16 -1 -3
17  0 -5
18 -1 -2
19 -1 -5
20 -1 -4

Converting all the values in df1 to positive values −

Example

> abs(df1)

Output

  x1 x2
1  1 2
2  1 4
3  0 1
4  0 0
5  1 2
6  0 0
7  0 4
8  0 4
9  0 2
10 1 2
11 0 1
12 1 3
13 1 5
14 1 0
15 0 3
16 1 3
17 0 5
18 1 2
19 1 5
20 1 4

Let’s have a look at another example −

Example

 Live Demo

y1<-sample(-10:10,20,replace=TRUE)
y2<-sample(-100:1,20)
y3<-sample(-100:-91,20,replace=TRUE)
y4<-sample(c(-100,-50,0,50,100),20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2

Output

   y1  y2 y3  y4
1   8 -12 -99 100
2  -2 -37 -93 -50
3  -5 -85 -93 -100
4   6 -16 -93   0
5   2 -51 -91 50
6  -5 -50 -94 100
7   0 -38 -92 100
8  -3 -20 -95 -50
9   1 -42 -96 100
10 -8 -31 -94 -50
11 -4 -75 -100 0
12 -5 -80 -94 100
13  0 -1  -95   0
14  2 -99 -99  50
15  9 -45 -97 -50
16 -6 -79 -93  50
17 -2 -52 -94  0
18  9 -82 -96  50
19  8 -32 -95  0
20  4 -11 -99 -100

Converting all the values in df2 to positive values −

Example

abs(df2)

Output

  y1 y2 y3 y4
1  8 12 99 100
2  2 37 93 50
3  5 85 93 100
4  6 16 93 0
5  2 51 91 50
6  5 50 94 100
7  0 38 92 100
8  3 20 95 50
9  1 42 96 100
10 8 31 94 50
11 4 75 100 0
12 5 80 94 100
13 0 1 95 0
14 2 99 99 50
15 9 45 97 50
16 6 79 93 50
17 2 52 94 0
18 9 82 96 50
19 8 32 95 0
20 4 11 99 100

Updated on: 17-Oct-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements