示例數據:抗加入,但只返回「上一個」失蹤一行
library(dplyr)
x <- data.frame(name = c(rep('Alice', 4), rep('Bob', 3)),
timestamp = c(1, 5, 10, 11, 1, 3, 4), stringsAsFactors = F)
y <-
base::merge(I(c('Alice', 'Bob')), c(1:3, 5:15)) # note missing time stamp = 4
names(y) <- names(x)
y <-
y %>%
arrange(name,timestamp)
我想了解,如果存在的話,在每個連續的塊中的最後一行中的數據幀anti_join(y,x)
(使用timestamp
訂購) 。
使用數據。例如,構建anti_join
:
x_missing <-
dplyr::anti_join(y, x) %>%
arrange(name,timestamp)
其給出
> head(x_missing, 11)
name timestamp
1 Alice 2
2 Alice 3
3 Alice 6
4 Alice 7
5 Alice 8
6 Alice 9
7 Alice 12
8 Alice 13
9 Alice 14
10 Alice 15
11 Bob 2
我想解決方案爲:
name timestamp
Alice 3
Alice 9
Alice 15
...
該解決方案需要更快比計算anti_join(y,x)
,這在時過於緩慢都很大。
的三個連續時間戳愛麗絲塊是(2,3),(6,7,8,9)和(12,13,14,15) – Alex
'Y%:沒有關於相對速度想法>%anti_join(x)%>%group_by(name)%>%filter(!timestamp%in%(timestamp - 1))%>%arrange(name,timestamp)'? – alistaire
@alistaire你應該把它放在一個答案,很好 –