Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

r - Calculating the difference between consecutive rows by group using dplyr?

I have a dataframe of ids and timestamps. I'd like to calculate the difference between each sequential timestamp for an individual id.

My dataframe looks like this:

id  time
Alpha   1
Alpha   4
Alpha   7
Beta    5
Beta    10

I'm trying to add a column like time.difference below:

id  time    time.difference
Alpha   1   NA
Alpha   4   3
Alpha   7   4
Beta    5   NA
Beta    10  5

Is there a clean way to do this using dplyr? (or tidyr or something else that's easier to read than vanilla R?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like this:

dat %>% 
  group_by(id) %>% 
  mutate(time.difference = time - lag(time))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...