How to find the absolute distance between columns of an R data frame?


The absolute distance can be found by calculating the difference between column values. And if we want the distance to be absolute then we would be need to use abs function. For example, suppose we have a data frame df that contain columns x and y then the absolute distance can be found by using df$Absolute_Distance<-abs(df$y-df$x).

Example1

Consider the below data frame:

Live Demo

> set.seed(274)
> x1<-rpois(20,5)
> y1<-rpois(20,8)
> df1<-data.frame(x1,y1)
> df1

Output

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

Creating a new column with absolute distance:

Example

> df1$Absolute_Distance<-abs(df1$y1-df1$x1)
> df1

Output

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

Example2

Live Demo

> x2<-sample(0:9,20,replace=TRUE)
> y2<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(x2,y2)
> df2

Output

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

Creating a new column with absolute distance:

Example

> df2$Distance<-abs(df2$y2-df2$x2)
> df2

Output

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

Updated on: 23-Nov-2020

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements