r - 使用 Dbplyr 时将日期转换为年季度格式

标签 r postgresql date dbplyr

我在数据库中有一个数据框,其中包含我使用 RPostgres/RpostgreSQL 和 dbplyr 提取的日期维度。每个日期的格式为“YYYY-MM-DD”,我需要添加一个新的日期(或字符)维度,以反射(reflect)年季度格式“YYYY-Q”中的原始日期(带有破折号,而不是期)。

鉴于我无法将 lubridate 与 dbplyr 一起使用,我该如何实现此目的?

感谢您的帮助!这是迄今为止我所拥有的简化版本,以便您可以看到我正在使用哪些包以及我如何连接到数据库。

# Packages
library(RPostgres)
library(RPostgreSQL)
library(dplyr)
library(dbplyr)

# Connect to db 
drv <- dbDriver("Postgres")

# Setup connect to db
conn <- dbConnect(drv,
                  dbname = etc,)

# Define table to use in db
table <- tbl(conn, in_schema("xyz", "abc"))

#Select columns and filter
df <- table %>%
  #Filter for pertinent data
  filter(date > as.Date("2018-01-01") & date <= as.Date("2020-01-01")) 

 

最佳答案

dbplyr 中为一堆 lubridate 函数提供了 SQL 翻译。所以下面的代码对我有用。

这样做的一个优点是,如果小心使用,您可以将数据位置转移到最有效的位置(在服务器上或本地)。

library(dplyr, warn.conflicts = FALSE)
library(DBI)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

pg <- dbConnect(RPostgres::Postgres(), bigint = "integer")
calls <- tbl(pg, sql("SELECT * FROM streetevents.calls"))

calls %>%
    mutate(yq = paste0(year(start_date), "-", quarter(start_date))) %>%
    select(start_date, yq)
#> # Source:   lazy query [?? x 2]
#> # Database: postgres [iangow@/tmp:5432/crsp]
#>    start_date          yq    
#>    <dttm>              <chr> 
#>  1 2013-09-10 19:30:00 2013-3
#>  2 2003-10-22 15:00:00 2003-4
#>  3 2009-10-22 16:00:00 2009-4
#>  4 2017-02-09 06:00:00 2017-1
#>  5 2010-02-22 22:00:00 2010-1
#>  6 2016-08-08 20:30:00 2016-3
#>  7 2016-05-11 13:00:00 2016-2
#>  8 2012-05-15 16:20:00 2012-2
#>  9 2004-08-19 21:00:00 2004-3
#> 10 2017-07-06 13:30:00 2017-3
#> # … with more rows

calls %>%
    collect(n = 10) %>%
    mutate(yq = paste0(year(start_date), "-", quarter(start_date))) %>%
    select(start_date, yq)
#> # A tibble: 10 x 2
#>    start_date          yq    
#>    <dttm>              <chr> 
#>  1 2013-09-10 19:30:00 2013-3
#>  2 2003-10-22 15:00:00 2003-4
#>  3 2009-10-22 16:00:00 2009-4
#>  4 2017-02-09 06:00:00 2017-1
#>  5 2010-02-22 22:00:00 2010-1
#>  6 2016-08-08 20:30:00 2016-3
#>  7 2016-05-11 13:00:00 2016-2
#>  8 2012-05-15 16:20:00 2012-2
#>  9 2004-08-19 21:00:00 2004-3
#> 10 2017-07-06 13:30:00 2017-3

reprex package 于 2021 年 4 月 3 日创建(v1.0.0)

关于r - 使用 Dbplyr 时将日期转换为年季度格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66913241/

相关文章:

返回 NaN 而不是 -1

javascript - 使用最后一个文本框值填充新添加的文本框

mysql - 根据近似值选择行

c# - 使用 C# 将 Postgres DB 导出到 Excel

python - 为什么 Django 迁移在每一行上使用相同的随机默认值?

java - 在 Java 中我怎么说 5 秒后?

R如何从一个数据帧划分到另一个数据帧对应的列名

css - 在 shinydashboard 上使用 CSS 创建的圆圈内不显示数字

r - 每组唯一值的计数器增加 1

postgresql - liquibase:dropAll 还应该删除触发函数