How to check whether the difference between previous and current value in a column of an R data frame is 1?

R ProgrammingServer Side ProgrammingProgramming

To check whether the difference between previous and current value in a column of an R data frame is 1, we can follow the below steps −

  • First of all, create a data frame.
  • Then, create a custom function for the difference between previous and current value.
  • Now, use the function to check the difference.

Example1

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x<-1:20
> df1<-data.frame(x)
> df1

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

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

Create a custom function to check the difference

Using abs function and diff function to create a new function to check whether all values in an R data frame column have a difference of 1 with each other −

> is.one<-function(x){
   + all(abs(diff(x))==1)
+ }

Check the difference

Using is.one function to check whether the current and previous values in column x of df1 have a difference of 1 or not −

> x<-1:20
> df1<-data.frame(x)
> is.one(df1$x)

Output

[1] TRUE

Example2

Create the data frame

Let’s create a data frame as shown below −

 Live Demo

> y<-sample(1:20,20)
> df2<-data.frame(y)
> df2

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

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

Check the difference

Using is.one function to check whether the current and previous values in column y of df2 have a difference of 1 or not −

> y<-sample(1:20,20)
> df2<-data.frame(y)
> is.one(df2$y)

Output

[1] FALSE
raja
Published on 03-Aug-2021 11:02:07
Advertisements