通过WRDS连接R中的crsp和compustat

时间:2016-01-16 00:35:46

标签: r sas data.table wrds-compusat wrds

我使用R连接到WRDS。现在,我想链接compustat和crsp表。在SAS中,这将使用宏和CCM链接表来实现。在R中处理这个主题的最佳方法是什么?

进展更新:

我从wrds下载了crsp,compustat和ccm_link表。

sql <- "select * from CRSP.CCMXPF_LINKTABLE"
res <- dbSendQuery(wrds, sql)
ccmxpf_linktable <- fetch(res, n = -1)
ccm.dt <- data.table(ccmxpf_linktable)
rm(ccmxpf_linktable)

然后我将建议的匹配例程从wrds事件研究sas文件转换为R:

ccm.dt[,typeflag:=linktype %in% c("LU","LC","LD","LN","LS","LX") & USEDFLAG=="1"]
setkey(ccm.dt, gvkey, typeflag)
for (i in 1:nrow(compu.dt)) {
  gvkey.comp = compu.dt[i, gvkey]
  endfyr.comp = compu.dt[i,endfyr]
  PERMNO.val <- ccm.dt[.(gvkey.comp, TRUE),][linkdt<=endfyr.comp & endfyr.comp<=linkenddt,lpermno]
  if (length(PERMNO.val)==0) PERMNO.val <- NA
  suppressWarnings(compu.dt[i, "PERMNO"] <- PERMNO.val)
}

然而,这段代码非常低效。我从data.table开始,但并不真正了解如何在for循环中应用逻辑。我希望有些人能指出我如何改进for循环。

1 个答案:

答案 0 :(得分:0)

分阶段匹配字段效果更好。也许有人觉得这很有用。当然非常欢迎任何进一步改进的建议!!!

# filter on ccm.dt
ccm.dt <- ccm.dt[linktype %in% c("LU","LC","LD","LN","LS","LX") & USEDFLAG=="1"]
setkey(ccm.dt, gvkey)
setkey(compu.dt, gvkey)
compu.merged <- merge(compu.dt, ccm.dt, all.x = TRUE, allow.cartesian = TRUE)
# deal with NAs in linkenddt - set NAs to todays date, assuming they still exist.
today <- as.character(Sys.Date())
compu.merged[is.na(linkenddt), "linkenddt":=today]
# filter out date mismatches
compu <- compu.merged[linkdt <= endfyr & endfyr<=linkenddt]