如何根据时间戳获取r中一周到另一周的差异
我试图通过创建一个新的列来检查客户是否每周都在购买,该列显示购买发生在随后的一周 初始数据 最终数据如何根据时间戳获取r中一周到另一周的差异,r,timestamp,data-manipulation,tidyr,data-transform,R,Timestamp,Data Manipulation,Tidyr,Data Transform,我试图通过创建一个新的列来检查客户是否每周都在购买,该列显示购买发生在随后的一周 初始数据 最终数据 其中一个选项是为此使用dplyr 您的预期输出表有点不正确,因为第一个时间戳与第周不匹配 library(dplyr) df %>% group_by(id) %>% mutate(diff1 = week_no - lag(week_no)) %>% filter(timestamp == max(timestamp)) # A tibble: 2 x 4
其中一个选项是为此使用
dplyr
您的预期输出表有点不正确,因为第一个时间戳与第周不匹配
library(dplyr)
df %>%
group_by(id) %>%
mutate(diff1 = week_no - lag(week_no)) %>%
filter(timestamp == max(timestamp))
# A tibble: 2 x 4
# Groups: id [2]
id timestamp week_no diff1
<chr> <dttm> <int> <int>
1 b9968 2016-08-23 17:46:44 34 1
2 4983f 2016-08-13 17:30:47 32 0
库(dplyr)
df%>%
分组依据(id)%>%
变异(diff1=周无-滞后(周无))%>%
过滤器(时间戳==最大值(时间戳))
#一个tibble:2x4
#组别:id[2]
id时间戳周号差异1
1 b9968 2016-08-23 17:46:44 34 1
24983F 2016-08-13 17:30:47 32 0
数据:
df非常感谢。这对我有用。我不明白为什么会有人投票反对这个答案。
id timestamp week_no diff1
b9968 2016-08-17 09:38:33 34 1
4983f 2016-08-13 17:30:47 32 0
library(dplyr)
df %>%
group_by(id) %>%
mutate(diff1 = week_no - lag(week_no)) %>%
filter(timestamp == max(timestamp))
# A tibble: 2 x 4
# Groups: id [2]
id timestamp week_no diff1
<chr> <dttm> <int> <int>
1 b9968 2016-08-23 17:46:44 34 1
2 4983f 2016-08-13 17:30:47 32 0
df <- structure(list(id = c("b9968", "b9968", "b9968", "b9968", "4983f",
"4983f"),
timestamp = structure(c(1471426713, 1471541603, 1471631120,
1471974404, 1471003283, 1471109447),
tzone = "UTC", class = c("POSIXct","POSIXt")),
week_no = c(33L, 33L, 33L, 34L, 32L, 32L)),
.Names = c("id", "timestamp", "week_no"),
row.names = c(NA, -6L),
class = "data.frame")