Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 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 Reply

0 votes
by (71.8m points)

Like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...