如何在 dbplyr 中执行 floor_date()

How to do a floor_date() in dbplyr

我正在尝试通过平均将分钟级别的时间序列数据聚合到每小时级别。

为了做到这一点,我想计算一个小时列,其中包含读取发生的日期和小时。然后我可以做一个简单的 group_by summarise。例如,我的 tbl_df 看起来像:

# Database: Microsoft SQL Server 13.00.4001[<SERVER>/<Project>]
   eGauge                    time Channel        End_Use Metric Circuit     Reading mean_lag
    <int>                   <chr>   <chr>          <chr>  <chr>   <chr>       <dbl>    <dbl>
 1  30739 2018-07-06 20:04:00.000     8.0 Clothes Washer      P    <NA> 0.000033333       60
 2  30739 2018-07-06 20:13:00.000     3.0  Clothes Dryer      P    <NA> 0.000833333       60
 3  30739 2018-07-06 21:16:00.000     6.0        Cooktop      P    <NA> 0.000050000       60
 4  30739 2018-07-06 21:00:00.000     3.0  Clothes Dryer      P    <NA> 0.000833333       60
 5  30739 2018-07-06 21:46:00.000     8.0 Clothes Washer      P    <NA> 0.000016667       60
 6  30739 2018-07-07 02:06:00.000     3.0  Clothes Dryer      P    <NA> 0.001016667        1
 7  30739 2018-07-07 08:52:00.000     1.0  Service Mains      P    <NA> 1.814516667        1
 8  30739 2018-07-07 08:52:00.000     3.0  Clothes Dryer      P    <NA> 0.001050000        1
 9  30739 2018-07-07 08:52:00.000     4.0     Central AC      P    <NA> 0.043000000        1
10  30739 2018-07-07 08:52:00.000     5.0           Oven      P    <NA> 0.021333333        1

我想要一个这样的新专栏:2018-07-06 20:00:00.0002018-07-06 20:00:00.000.

通常我会使用 lubridate 中的 floor_date(time, "hour"),甚至 str_replace(time, ".{2}(?=:[^:]*$)", "00"),但它们都不适用于我的 SQL 服务器连接。

知道这在 R 中是如何完成的吗?答案必须是R码,最好是dplyr码如:

# NOT WORKING
my_table %>%
  mutate(time_hour = floor_date(time, "hour"))

# NOT WORKING
my_table %>%
  mutate(time_hour = DATEADD('hour', DATEDIFF('hour', 0, time), 0))

有效但需要改进

my_table %>%
      mutate(hour = "hour",
             time_hour = DATEADD(hour, DATEDIFF(hour, 0, time), 0)) %>%
      select(-hour)
my_table %>%
    mutate(time_hour = DATEADD(sql("hour"), DATEDIFF(sql("hour"), 0, time), 0))