1

WRDS 是为商业和相关领域的学者和其他研究人员提供研究数据的领先提供商。WRDS 提供了一个 PostgreSQL 数据库,但这是一个只读数据库。

对于某些任务,无法将数据写入数据库是非常受限制的。例如,如果我想使用每日股票收益运行事件研究,我需要将我的(相对较小的)本地数据集eventscrsp.dsf大约 18GB 的​​数据合并。

一种选择是使用该数据库的副本维护我自己的数据库crsp.dsf并写入events该数据库并在那里合并。但我正在寻找一个允许我为此目的使用 WRDS 数据库的选项。不幸的是,没有办法使用copy_toor dbWriteTable,因为 WRDS 数据库是只读的。

4

1 回答 1

1

一种选择是使用类似下面的函数,即使使用只读连接,它也会使用 SQL 将本地数据帧转换为远程数据帧。

df_to_pg <- function(df, conn) {

    collapse <- function(x) paste0("(", paste(x, collapse = ", "), ")")

    names <- paste(DBI::dbQuoteIdentifier(conn, names(df)), collapse = ", ")

    values <-
        df %>%
        lapply(DBI::dbQuoteLiteral, conn = conn) %>%
        purrr::transpose() %>%
        lapply(collapse) %>%
        paste(collapse = ",\n")

    the_sql <- paste("SELECT * FROM (VALUES", values, ") AS t (", names, ")")

    temp_df_sql <- dplyr::tbl(conn, dplyr::sql(the_sql))
    
    return(temp_df_sql)
}

这是使用中的功能的图示。功能已经在 PostgreSQL 和 SQL Server 上测试过,但不能在 SQLite 上工作(由于缺少VALUES以这种方式工作的关键字)。我相信它应该适用于 MySQL 或 Oracle,因为它们有VALUES关键字。

library(dplyr, warn.conflicts = FALSE)
library(DBI)
   
pg <- dbConnect(RPostgres::Postgres())     

events <- tibble(firm_ids = 10000:10024L,
                 date = seq(from = as.Date("2020-03-14"), 
                            length = length(firm_ids), 
                            by = 1))
events
#> # A tibble: 25 x 2
#>    firm_ids date      
#>       <int> <date>    
#>  1    10000 2020-03-14
#>  2    10001 2020-03-15
#>  3    10002 2020-03-16
#>  4    10003 2020-03-17
#>  5    10004 2020-03-18
#>  6    10005 2020-03-19
#>  7    10006 2020-03-20
#>  8    10007 2020-03-21
#>  9    10008 2020-03-22
#> 10    10009 2020-03-23
#> # … with 15 more rows

events_pg <- df_to_pg(events, pg)
events_pg
#> # Source:   SQL [?? x 2]
#> # Database: postgres [iangow@/tmp:5432/crsp]
#>    firm_ids date      
#>       <int> <date>    
#>  1    10000 2020-03-14
#>  2    10001 2020-03-15
#>  3    10002 2020-03-16
#>  4    10003 2020-03-17
#>  5    10004 2020-03-18
#>  6    10005 2020-03-19
#>  7    10006 2020-03-20
#>  8    10007 2020-03-21
#>  9    10008 2020-03-22
#> 10    10009 2020-03-23
#> # … with more rows

reprex 包于 2021-04-01 创建(v1.0.0)

于 2021-04-01T19:01:23.487 回答