How to aggregate Data by 3 minutes timestamps in sparklyr?

狂风中的少年 提交于 2019-12-04 17:09:21

Assuming your data is already parsed:

df1
# # Source:   table<df1> [?? x 4]
# # Database: spark_connection
#      id timefrom            timeto              value
#   <int> <dttm>              <dttm>              <int>
# 1    10 2017-06-06 08:30:00 2017-06-06 08:31:00    50
# 2    10 2017-06-06 08:31:00 2017-06-06 08:32:00    80
# 3    10 2017-06-06 08:32:00 2017-06-06 08:33:00    20
# 4    22 2017-06-06 08:33:00 2017-06-06 08:34:00    30
# 5    22 2017-06-06 08:34:00 2017-06-06 08:35:00    50
# 6    22 2017-06-06 08:35:00 2017-06-06 08:36:00    50

df2
# # Source:   table<df2> [?? x 4]
# # Database: spark_connection
#      id timefrom            timeto              value
#   <int> <dttm>              <dttm>              <int>
# 1    10 2017-06-06 08:30:00 2017-06-06 08:33:00    30
# 2    22 2017-06-06 08:33:00 2017-06-06 08:36:00    67
# 3    32 2017-06-06 08:36:00 2017-06-06 08:39:00    28
# 4    14 2017-06-06 08:39:00 2017-06-06 08:42:00    30
# 5    27 2017-06-06 08:42:00 2017-06-06 08:55:00    90

you can use window function:

exprs <- list(
  "id", "value as value2",
  # window generates structure struct<start: timestamp, end: timestamp>
  # we use dot syntax to access nested fields
  "window.start as timefrom", "window.end as timeto")

df1_agg <- df1 %>% 
  mutate(window = window(timefrom, "3 minutes")) %>% 
  group_by(id, window) %>% 
  summarise(value = avg(value)) %>%
  # As far as I am aware there is no sparklyr syntax 
  # for accessing struct fields, so we'll use simple SQL expression
  spark_dataframe() %>% 
  invoke("selectExpr", exprs) %>% 
  sdf_register() %>%
  print()

# Source:   table<sparklyr_tmp_472ee8ba244> [?? x 4]
# Database: spark_connection
     id value2 timefrom            timeto             
  <int>  <dbl> <dttm>              <dttm>             
1    22   43.3 2017-06-06 08:33:00 2017-06-06 08:36:00
2    10   50.0 2017-06-06 08:30:00 2017-06-06 08:33:00

Then you can just by id and timestamp columns:

df2 %>% inner_join(df1_agg, by = c("id", "timefrom", "timeto"))
# # Source:   lazy query [?? x 5]
# # Database: spark_connection
#      id timefrom            timeto              value value2
#   <int> <dttm>              <dttm>              <int>  <dbl>
# 1    10 2017-06-06 08:30:00 2017-06-06 08:33:00    30   50.0
# 2    22 2017-06-06 08:33:00 2017-06-06 08:36:00    67   43.3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!