如何在R中编写for循环来设置列表中数据集的周期以及开始和结束日期

问题描述

我正在尝试设置列表中数据集的 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)

如果有人能帮助我,那就太好了。 :)

解决方法

你不需要一个显式的 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