首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >for循环中的新对象

for循环中的新对象
EN

Stack Overflow用户
提问于 2021-08-05 09:55:25
回答 1查看 24关注 0票数 0

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

代码语言:javascript
复制
Error in merge(fund_table_xts, fund_table_xts_fin) : 
  object 'fund_table_xts_fin' not found

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

我的代码:

代码语言:javascript
复制
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)
  }
  
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-05 10:30:03

代码语言:javascript
复制
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)
  }`
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68664408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档