r - 如何正确使用 lapply 和 Bloomberg Rblpapi 包来提取多组代码
问题描述
我不确定这是一个 lapply 问题还是关于 Rblpapi 语法的问题。Rblpapi 是一个很棒的包,用于通过 R 从Bloomberg 中提取数据。
因为不是每个人都可以访问彭博社,而且涉及到很多代码,这使得提供一个可重复的例子更具挑战性,所以希望有人可以提供一个没有 reprex 的解决方案。
当我使用以下代码时,我可以成功拉取我想要的数据:
library(Rblpapi)
library(tidyverse)
# Connect to Bloomberg --------------------------------------------------------------------
blpConnect()
# Specify beginning and end dates
beg_date <- as.Date("1927-12-30", format = "%Y-%m-%d")
end_date <- Sys.Date()
# Specify Bloomberg field to pull
my_field <- "PX_LAST"
# Call ticker script to load tickers
source(file.path(my_path, "tickers.R"), echo = FALSE)
# Create function to pull Bloomberg data
pull_fx <- function(input_tickers, input_field) {
df <- as.data.frame(
bdh(
input_tickers,
input_field,
start.date = beg_date,
end.date = end_date,
include.non.trading.days = TRUE
)
)
}
# Pull data
rates_level_df <- pull_fx(rates_tickers_level, my_field)
equity_level_us_df <- pull_fx(equity_tickers_us_level, my_field)
当我尝试使用所有代码提取数据以便不必pull_fx(tickers_here, my_field)
为每组代码重复代码时,我尝试了以下操作:
list_df <- lapply(tickers_all, pull_fx, input_field = my_field)
其中tickers_all
是具有所有股票代码分组的字符向量(例如,“rates_tickers_level”)。我为每个股票代码集合返回一个数据框列表,但列表中的每个数据框都是空的。因此,我无法判断我是否只是错误地使用了 lapply,或者我是否提供了错误的语法来使用 bdh 命令(Rblpapi 包)。
我期望的输出是一个数据帧列表,其中包含为每组代码提取的数据(即,“rates_level_df”、“equity_level_us_df”等包含在tickers_all字符向量中的数据帧。
感谢帮助!
解决方案
尝试mget
使用tickers_all
list_df <- lapply(mget(tickers_all), pull_fx, input_field = my_field)
要理解为什么我们需要mget
在这里考虑这个简单的例子
a <- 1
b <- 2
tmp <- c('a', 'b')
tmp
#[1] "a" "b"
tmp
有变量a
,b
它们以字符串形式存储在其中。要获得存储在其中的值 1 和 2,a
我们b
需要mget
.
mget(tmp)
#$a
#[1] 1
#$b
#[1] 2
推荐阅读
- python-3.x - PyWinAuto 选择文件 -> 从 Tableau Desktop 打开
- flutter - 使 CupertinoIcon 渲染而不显示占位符
- python - Heroku Django APScheduler 在作业完成后不释放内存
- terraform - 在嵌套模块中引用来自在线嵌套模块的输出
- autocomplete - GTK EntryCompletion 通过插入而不是替换
- python-3.x - 附加到多个 dict 值而不是一个的数据
- reactjs - Netlify、Lambdas、Stripe 和 Googlebots
- javascript - 如何检测移动设备或台式机上的浏览器?
- html - 我无法将响应式大图像更正到手机屏幕
- nuxt.js - NuxtJS + BootstrapVue + TailwindCSS:我可以有效地使用 Bootstrap Vue 组件但使用 Tailwind CSS 进行样式设置吗?