当我 运行 我在 R Studio 中的代码时出现错误

I got an error when I run my codes in R Studio

这是我使用的代码

library(quantmod)
library(timetk)
library(dplyr)
library(tibble)
library(tidyr)


mdate <- "2015-10-30"
edate <- "2016-01-05"

tickers <- c("ABG","ACH","ADM","AEG","AEM","AGQ","AGRO","AKOb","APO")


data <- do.call(cbind.data.frame, lapply(tickers, function(x) 
  getSymbols(x, from = mdate, to = edate, auto.assign = F)))


# Transpose data.frame: 
td_data <- within(data.frame(price_var = row.names(t(data)), t(data), row.names = NULL), 
                  {
                    ticker_cd <- as.factor(gsub("[.].*", "", price_var))
                    price_var <- as.factor(gsub(".*[.]", "", price_var))
                  }
)
# Reshape: 
abc <- do.call("cbind", split(td_data, td_data$price_var))

当我 运行 这些时,我得到了:

data.frame(..., check.names = FALSE) 中的错误: 参数暗示不同的行数:44、38 另外: 警告信息: AKOb 包含缺失值。如果对象在序列中间包含缺失值,则某些函数将不起作用。考虑使用 na.omit()、na.approx()、na.fill() 等来删除或替换它们。

我发现这个错误是由"AKOB"引起的。第一天和第六天的数据是空白的,所以 "AKOB" 星的第一天是 2015 年 11 月 9 日,这与其他股票数据不同。我找到的方法是运行一个一个比较他们的不同。每当它发生时,这是非常低效的方式。

如果股票在我的设置中没有数据(从开始日期到结束日期),我想跳过 我该怎么做才能做到这一点?

library(quantmod)

mdate <- "2015-10-30"
edate <- "2016-01-05"

tickers <- c("ABG","ACH","ADM","AEG","AEM","AGQ","AGRO","AKOb","APO", "JJE")

# Iterate through the tickers and retrieve data from Yahoo Finance defensively: data => xts
data <- do.call("cbind", lapply(seq_along(tickers), function(i){
        try_var <- try(getSymbols(tickers[i], from = mdate, to = edate, auto.assign = FALSE))
        if(inherits(try_var, "try-error")) {
          i <- i + 1
        } else{
          getSymbols(tickers[i], from = mdate, to = edate, auto.assign = FALSE)   
        }
      }
    )
  )



# Transpose data.frame: td_data => data.frame
td_data <- within(data.frame(price_var = row.names(t(data)), t(data), row.names = NULL), 
                  {
                    ticker_cd <- as.factor(gsub("[.].*", "", price_var))
                    price_var <- as.factor(gsub(".*[.]", "", price_var))
                  }
                )

# Re-order vectors; keep complete cases: td_data_o => data.frame
td_data_o <- td_data[complete.cases(td_data), 
                     c(names(td_data)[sapply(td_data, is.factor)],  
                       names(td_data)[sapply(td_data, function(x){!is.factor(x)})])]

# Reshape: abc => data.frame
abc <- do.call("cbind", split(td_data_o, td_data_o$price_var))