# diff function in R: Calculate the difference of elements

In this article, we will show you what the diff function in R is and how to use the diff function in R. The diff function can help you calculate the differences between elements in a numeric object. Let’s check it out!

## What does the diff function do in R?

The diff function can help you calculate the differences between the elements in the vector, the array whose value is numeric. It also can calculate the differences between the elements in a column or multiple columns in the data frame. Let’s take a look at the syntax of the diff function in the next part.

Syntax:

diff(data, lag, differences)

Parameters:

• data: The numeric object.
• lag: The default is 1. The lag is used for this function.
• differences: The default is 1. The order of the differences.

After learning the syntax of the diff function, you will learn how to perform it in the next title below.

## How to use the diff function in R?

### Use the diff function with the vector

You can use the diff function to calculate the differences between the elements in the numeric vector.

Look at the example below.

# Create the vector.
vec <- c(1,4,5,7,9)

# Use the diff function to calculate the difference between consecutive elements.
diff(vec)

Output

[1] 3 1 2 2

### Calculate the differences between the non-consecutive elements

You can calculate the differences between the non-consecutive elements by assigning value to the lag in the diff function.

Look at the example below.

# Create the vector.
vec <- c(1,4,5,7,9,13,22,30,40)

# Use the diff function to calculate the difference between 2 consecutive elements.
diff(vec, lag = 2)

Output

[1] 4 3 4 6 13 17 18

### Use the diff function with the data frame

You can use the diff function to calculate the differences between the elements in a column in the data frame.

Look at the example below.

# Create the data frame.
df <- data.frame( age = c(20, 22 ,25 ,27 ,31),
salary = c(190, 280, 340, 320, 310))

# Use the diff function to calculate the difference between consecutive elements in 'age'.
diff(df\$age)

Output

[1] 2 3 2 4

### Use the diff function with multiple columns in the data frame

You can use the diff function to calculate the differences between the elements in multiple columns in the data frame.

Look at the example below.

# Create the data frame.
df <- data.frame( age = c(20, 22 ,25 ,27 ,31),
salary = c(190, 280, 340, 320, 310))

# Use the diff function and the sapply function.
sapply(df, diff)

Output

    age salary
[1,] 2   90
[2,] 3   60
[3,] 2  -20
[4,] 4  -10


## Summary

You have learned about the usage, the syntax, and how to use the diff function in RBy the diff function, you can calculate the differences between elements in the numeric object. We hope this tutorial is helpful to you. Thanks!

Maybe you are interested:

Posted in R