r语言 - for循环中的新对象



我的代码有什么问题?我想创建一个新的xts对象来存储第一个循环中的数据,并在随后的循环中使用,但我得到了这个错误消息:

Error in merge(fund_table_xts, fund_table_xts_fin) : 
object 'fund_table_xts_fin' not found

必须在进入循环之前初始化对象吗?

我代码:

library(rvest)
library(dplyr)
library(XML)
library(xts)
library(bizdays)
library(RQuantLib)
fund_ID <- "510300"
from <- "2021-01-01"
to <- "2021-07-13"
# count days
load_quantlib_calendars('China', from = as.Date(from) - 14, to = as.Date(to) + 14)
iters <- ceiling(bizdays(from, to, 'QuantLib/China')/40)
seq <- bizseq(from, to, 'QuantLib/China')
for (i in 1:iters){

# set dates
f <- seq[40 * i - 39]
t <- seq[min(length(seq), 40 * i)]

# extract
fund_link <- paste("https://fundf10.eastmoney.com/F10DataApi.aspx?type=lsjz&code=", fund_ID, "&page=1&sdate=", from, "&edate=", to, "&per=40", sep = "")
fund_table <- read_html(fund_link) %>% html_nodes(".lsjz") %>% html_table() %>% .[[1]]
fund_table <- fund_table[,1:4]
colnames(fund_table) <- c("Date", "Net Asset Value", "Accumulated Asset Value", "Daily Return")
fund_table$Date <- as.Date(fund_table$Date,"%Y-%m-%d")

# xts 
fund_table_xts <- xts(fund_table[,-1],  order.by = fund_table$Date)
fund_table_xts$`Net Asset Value` <- as.numeric(fund_table_xts$`Net Asset Value`) 
fund_table_xts$`Accumulated Asset Value` <- as.numeric(fund_table_xts$`Accumulated Asset Value`)
fund_table_xts$`Daily Return` <- as.numeric(sub("%", "", fund_table$`Daily Return`))/100

#combine
if(i < 1){
fund_table_xts_fin <- fund_table_xts
} else {
fund_table_xts_fin <- merge(fund_table_xts, fund_table_xts_fin)
}

}
if(i < 1){
fund_table_xts_fin <- fund_table_xts
} else {
fund_table_xts_fin <- merge(fund_table_xts, fund_table_xts_fin)
}

In the above section when i = 1 then you are in the else block but there is no 'fund_table_xts_fin' object created yet. You can try this:
`if(i == 1){
fund_table_xts_fin <- fund_table_xts
} else {
fund_table_xts_fin <- merge(fund_table_xts, fund_table_xts_fin)
}`

最新更新