数据框如下:
db = (name = c('A','A','A', 'B','B','B','B', 'C','C'),
time = c('09/09/15 0:37:45', '09/09/15 0:39:45', '09/09/15 1:39:15', '09/10/15'20:35:20, '09/10/15 20:45:40', '09/10/15 20:47:00', '09/10/15 21:47:00' ,'09/11/15 7:15:15', '09/11/15 17:15:30')
我想得到的是每个名字之间的分钟间隔,我想得到的数据是这样的:
db = (name = c('A','A','A', 'B','B','B','B', 'C','C'),
gap = c(NA, 2, 59.5, NA, 10.33, 1.67, 60, NA, 600.25)
任何人都可以解决这个难题吗?谢谢!
答案 0 :(得分:1)
library(dplyr)
db %>% group_by(name) %>% mutate(gap=round(c(NA,diff(time)), 1))
Source: local data frame [9 x 3]
Groups: name [3]
name time gap
(fctr) (time) (dbl)
1 A 2015-09-09 00:37:45 NA
2 A 2015-09-09 00:39:45 2.0
3 A 2015-09-09 01:39:15 59.5
4 B 2015-09-10 20:35:20 NA
5 B 2015-09-10 20:45:40 10.3
6 B 2015-09-10 20:47:00 1.3
7 B 2015-09-10 21:47:00 60.0
8 C 2015-09-11 07:15:15 NA
9 C 2015-09-11 17:15:30 10.0