How to find the difference between row values starting from bottom of an R data frame?


If an R data frame contains all numerical columns and we want to find the difference between row values then we will lose first row of the data frame because that will not be subtracted from any row. This can be done by using head function and minus sign. It will work as subtracting the second last row from the last row, then subtracting third last row from the second last row and so on.

Example

Consider the below data frame −

 Live Demo

x1<-rpois(20,2)
y1<-rpois(20,3)
z1<-rpois(20,5)
w1<-rpois(20,8)
v1<-rpois(20,10)
df1<-data.frame(x1,y1,z1,w1,v1)
df1

Output

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

Finding the difference between starting from bottom −

Example

tail(df1,-1)-head(df1,-1)

Output

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

Let’s have a look at another example −

Example

 Live Demo

x2<-sample(1:10,20,replace=TRUE)
y2<-sample(1:10,20,replace=TRUE)
z2<-sample(1:10,20,replace=TRUE)
w2<-sample(1:10,20,replace=TRUE)
v2<-sample(1:10,20,replace=TRUE)
df2<-data.frame(x2,y2,z2,w2,v2)
df2

Output

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

Example

tail(df2,-1)-head(df2,-1)

Output

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

Updated on: 08-Sep-2020

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements