使用纯R与dbplyr处理日期 [英] Handle dates with dbplyr using pure R

查看:137
本文介绍了使用纯R与dbplyr处理日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dbplyr将dplyr和基本的R命令转换为SQL,以便开发人员可以编写R代码并使其在数据库中执行(tidyverse参考书).在R中使用日期时,通常使用lubridate包.但是,目前不存在用于lubridate函数的dbplyr转换.因此,使用dbplyr的开发人员需要找到其他处理日期的方法.

dbplyr translates dplyr and base R commands into SQL so that developers can write R code and have it executed in a database (tidyverse reference). When working with dates in R, it is common to use the lubridate package. However, dbplyr translations for lubridate functions do not exist at present. So developers using dbplyr need to find alternative ways of working with dates.

我以前的方法是在dplyr命令中使用SQL语法的片段(请参见示例答案:此处此处).但是,当dbplyr的部分要点是为您转换为SQL时,这要求开发人员知道(或找出)相应的SQL命令.

My previous approach has been to use fragments of SQL syntax in my dplyr commands (see for example answers: here and here). However, this requires the developer to know (or find out) the corresponding SQL commands, when part of the point of dbplyr is that it translates to SQL for you.

这使我问:仅当连接到远程数据库时,使用dbplyr转换操作日期的最佳方法是什么?

理想的解决方案将是:

  • 仅使用dbplyr转换,因此不能使用没有dbplyr转换的功能.
  • 使用纯R,没有SQL片段.
  • 在数据库上运行,因此是远程表而不是本地表.

我认为至少我们应该能够:

I think at a minimum we should be able to:

  • 提取年,月和日
  • 将年,月和日组合为新日期

您可以从中手动执行其他操作,例如:

From these you can manually do other operations such as:

  • 增加日期
  • 找出两个日期之间的差异
  • 查找月底的日期

但是更快速/优雅的方法来执行这些更高级的操作将是可取的.

But faster/elegant ways to do these more advance operations would be preferable.

推荐答案

一个答案是,其中很多已经是可能的.(请参见答案此处.)

One answer is that much of this is already possible. (See answer here.)

dbplyr 中缺少所需功能的情况下,一种想法是编写请求请求,从而将 lubridate 函数的更多翻译添加到中的后端dbplyr .

To the extent that desired functions are missing from dbplyr, one idea would be to write pull requests that add more translations of lubridate functions to the backends in dbplyr.

翻译似乎不可避免地是特定于后端的.如果您在此处查看PostgreSQL后端,则您可以看到某些 lubridate 函数(例如 month quarter )在那里得到了翻译,而其他函数(例如 ymd )不是.

It seems that translations are inevitably backend-specific. If you look at the PostgreSQL backend here, you can see that some lubridate functions (e.g., month or quarter) are given translations there, but others (e.g., ymd) are not.

这篇关于使用纯R与dbplyr处理日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆