如何在 R 中编写一个 for 循环来设置列表中数据集的周期以及开始和结束日期
Posted
技术标签:
【中文标题】如何在 R 中编写一个 for 循环来设置列表中数据集的周期以及开始和结束日期【英文标题】:How to write a for loop in R to set periodicity as well as start and end date of datasets in list 【发布时间】:2021-09-23 00:55:12 【问题描述】:我正在尝试设置列表中数据集的 start_date 和 end_date 以及它在 R 中的周期性。但我无法编写用于选择列表中数据集的 for 循环。
代码如下
require(quantmod)
require(xts)
econ_data <- new.env()
symbols <- c('ICSA', 'INDPRO', 'NFCI'
)
getSymbols(Symbols = symbols, src='FRED', env = econ_data)
data <- eapply(env = econ_data, FUN = merge.xts)
#Now I want to set the start and end date of all datasets and it's periodicity together, same. (I tried with xts functions but was not able to, I think a proper for loop can do the job, not sure)
如果有人能帮助我,那就太好了。 :)
【问题讨论】:
【参考方案1】:您不需要显式的 for 循环。
ICSA <- get("ICSA", envir = econ_data)
INDPRO <- get("INDPRO", envir = econ_data)
NFCI <- get("NFCI", envir = econ_data)
# merge to xts
data <- do.call(merge.xts, args = list(ICSA, INDPRO, NFCI))
# remove NAs and carry forward last observation
data_clean <- na.locf(data, na.rm = T, maxgap = 10)
# monthly observations
data_monthly <- data_clean[xts::endpoints(data_clean, on = "months")]
# reduce timeindex
data_reduced <- data_monthly['2005-01/2010-12']
> head(data_reduced)
ICSA INDPRO NFCI
2005-01-29 331000 96.1164 -0.72024
2005-02-26 314000 96.8200 -0.71388
2005-03-26 342000 96.6725 -0.70228
2005-04-30 334000 96.8638 -0.66024
2005-05-28 340000 96.9622 -0.62226
2005-06-25 311000 97.3530 -0.63855
【讨论】:
以上是关于如何在 R 中编写一个 for 循环来设置列表中数据集的周期以及开始和结束日期的主要内容,如果未能解决你的问题,请参考以下文章