r - 使用 dplyr/dbplyr 添加 postgres 时间间隔

标签 r postgresql dplyr dbplyr

我在 R 中有一个数据库连接,想在 Postgres 中使用 dplyr (v0.5) 实现以下过滤步骤:

WHERE time1 < time2 - INTERVAL '30 minutes'

(参见 https://www.postgresql.org/docs/9.1/static/functions-datetime.html)

我尝试了以下操作(这是我对 POSIX 对象所做的)但收到此错误:

tbl(con, 'data') %>%
  filter(time1 < time2 - 30 * 60) %>%
  collect()
# ERROR: operator does not exist: timestamp without timezone - numeric

正确的做法是什么?

最佳答案

根据SQL translation vignette :

Any function that dplyr doesn’t know how to convert is left as is. This means that database functions that are not covered by dplyr can be used directly via translate_sql().

但是你不能使用 %interval%,因为你的条件在 R 中语法上不正确:

time1 < time2 - %interval% "30 minutes"
# Error: unexpected SPECIAL in "time1 < time2 - %interval%"

使用 interval 并不是更好:

time1 < time2 - interval "30 minutes"
# Error: unexpected string constant in "time1 < time2 - interval "30 minutes""

但下面的技巧确实有效:

dbplyr::translate_sql(time1 < time2 %- interval% "30 minutes")
# <SQL> "time1" < "time2" - INTERVAL '30 minutes'

所以这段代码应该回答你的问题:

tbl(con, "data") %>%
  filter(time1 < time2 %- interval% "30 minutes") %>%
  collect

关于r - 使用 dplyr/dbplyr 添加 postgres 时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372300/

相关文章:

r - tidyr::complete 带有可变长度的列名向量

R:如何删除data.table中的列?

postgresql - 来自另一个容器内部的 Docker 端口不匹配

r - 如何根据列名分配数据框列类?

sql - 使用 SQLKorma 获取语法 : Failure to execute query with SQL 的异常

mysql - 如何通过连接表中的引用对查找记录?

r - 如何在dplyr中将多个列名作为输入传递给group_by

r,write_csv 将所有时间/日期更改为 UTC

r - 如何在没有特定日期且不超过 24 小时的情况下使用 lubridate 添加小时数?

r - 如何计算 r 中非线性最小二乘法的置信区间?