Finding the difference between the consecutive lines within group in R

Chudar

I am new to R. I have a data frame like following:

group start end
    A  34   77
    A  100  140
    A  185  246 
    B  60    98
    B  146   186 
    C  250   315
    C  411   489
    C  510   550
    C  601   662

I would like to find the difference between the consecutive lines as follows:

group start end 
    A  78  99
    A  141 184
    B  99  145
    C  316 410
    C  490 509
    C  551 600

Any little help would be highly appreciated. Thanks in advance

akrun

We can try with data.table

library(data.table)
setDT(df1)[,.(start = (start+end - start +1)[-.N], 
           end = (end +shift(start, type='lead')-end-1)[-.N] ) , by = group]  
#   group start end
#1:     A    78  99
#2:     A   141 184
#3:     B    99 145
#4:     C   316 410
#5:     C   490 509
#6:     C   551 600

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Finding difference between consecutive numbers in an array in javascript

How to get the difference between columns within group in R?

Difference between two variables in R within the same group

Difference between rows within a group

Comparing values between lines within a group

Finding difference between two times in R

Finding Time Difference Between Observations in R

Create empty missing lines for values in multi-group multi-level data-structures and calculate difference between rows within groups

How to find a difference between consecutive rows of a same group?

Calculate time difference between consecutive rows in pairs per group in pyspark

Calculating the difference between consecutive rows by group using dplyr?

How do I group consecutive dates within a Vector in R?

R - Sum within group and only if another variable has consecutive values

Finding six consecutive integers in three lines of string

Vectorized way of finding difference between consecutive elements? Maybe a variation of np.diff()?

R Difference between consecutive rows while retaining first row

Difference between consecutive row groups using data table in R

Finding difference between time

Linux differences between consecutive lines

Finding value +1 within a group

Take difference between observations within same group with a reference observation

Error when trying to take the difference between observations within a group

How to calculate difference between datetime within a group in Python?

How to change a column based on the difference between dates within a group?

Finding a consecutive group of n elements in a circular array

group by consecutive values in r

Group consecutive dates in R

Group by Consecutive Dates R

Calculate difference between multiple rows by a group in R