如何从 xts 动物园对象矩阵中的每个对象访问核心数据
How do I access coredata from each object in a matrix of xts zoo objects
我使用 R 中 Quantmod 包中的 getFX 函数从 Oanda 生成一个速率向量,每个向量都采用 xts 动物园格式。
currency_pairs <- c("GBP/USD", "USD/SGD")
rates <- getFX(currency_pairs, from="2019/01/01", to="2019/01/01"
此 returns 形式的 xts 动物园对象向量:
(GBPUSD, USDSGD,...)
但是我只想知道汇率,因为我只需要一个日期的汇率,因此知道时间戳。
我试过像这样遍历向量:
for (i in 1:length(rates){
rates[i] <- coredata(rates[i])
}
但这只是 returns 货币对名称。
在这种情况下,如果您只检索一个日期的数据,您可以像这样使用 sapply
:
library(quantmod)
currency_pairs <- c("GBP/USD", "USD/SGD")
# for 1 date this will return a named vector otherwise use lapply
rates <- sapply(currency_pairs, getFX, from="2019/01/01", to="2019/01/01", auto.assign = FALSE)
rates
GBP/USD USD/SGD
1.275455 1.362920
通常我会建议使用 lapply 检索大列表中的所有货币,然后使用 lapply / mapply / Map / purrr::map 等访问列表
我使用 R 中 Quantmod 包中的 getFX 函数从 Oanda 生成一个速率向量,每个向量都采用 xts 动物园格式。
currency_pairs <- c("GBP/USD", "USD/SGD")
rates <- getFX(currency_pairs, from="2019/01/01", to="2019/01/01"
此 returns 形式的 xts 动物园对象向量:
(GBPUSD, USDSGD,...)
但是我只想知道汇率,因为我只需要一个日期的汇率,因此知道时间戳。
我试过像这样遍历向量:
for (i in 1:length(rates){
rates[i] <- coredata(rates[i])
}
但这只是 returns 货币对名称。
在这种情况下,如果您只检索一个日期的数据,您可以像这样使用 sapply
:
library(quantmod)
currency_pairs <- c("GBP/USD", "USD/SGD")
# for 1 date this will return a named vector otherwise use lapply
rates <- sapply(currency_pairs, getFX, from="2019/01/01", to="2019/01/01", auto.assign = FALSE)
rates
GBP/USD USD/SGD
1.275455 1.362920
通常我会建议使用 lapply 检索大列表中的所有货币,然后使用 lapply / mapply / Map / purrr::map 等访问列表