Calculate the difference in R

Calculate the difference in R, we will describe how to use R’s diff function to determine a vector’s differences. Let’s look at the definition of diff and the fundamental R syntax first:



The diff function calculates the difference between adjacent pairs of numeric vector items.

Data Science Statistics Jobs  » Are you looking for Data Science Jobs?

Calculate the difference in R

We will give you two examples of how to use diff in R programming in the sections that follow. So let’s go to the samples without further ado.

Example: diff Function With Default Specifications

Typically, a data frame’s column, array, or numeric vector will receive the diff function treatment. So let’s first make such a vector:

x <- c(15, 12, 20, 11, 13)

Our sample vector has five values, each ranging from 1 to 3. Let’s now compute the difference between each succeeding value in this vector using the diff command:


So what took place here? Four distinct calculations were made by the diff function:

Machine Learning Archives » Data Science Tutorials

             12 – 15 = – 3
             20 – 12 = 8
             11 – 20 = – 9
             13 – 11 = 2

The first value was subtracted from the second, the second from the third, the third from the fourth, and the fourth from the fifth using the R diff function.

The first latency was returned by diff to the RStudio console, to put it another way.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

three × 4 =