2中的错误:n:NA / NaN参数

时间:2018-03-21 05:09:13

标签: r

以下代码会产生以下错误:

  

Error in 2:n : NA/NaN argument

如何解决此错误?

library (pdfetch)
library(tidyverse)
library(xts)
tickers<-c("AXP","MMM","BA","CAT","CVX","CSCO","KO","DWDP","AAPL","XOM","GE","GS","HD","IBM","INTC","HPI","AIV","MCD","MRK","MSFT","NKE","PFE","PG","TRV","JPM","UTX","VZ","V","WMT","DIS")

data<-pdfetch_YAHOO(tickers<- c("^DJI","AXP","MMM","BA","CAT","CVX","CSCO","KO","DWDP","AAPL","XOM","GE","GS","HD","IBM","INTC","HPI","AIV","MCD","MRK","MSFT","NKE","PFE","PG","TRV","JPM","UTX","VZ","V","WMT","DIS"),from = as.Date("2015-03-20"),to =     as.Date("2018-03-20"),interval='1mo')

# to remove the nas from the entire data
data[complete.cases(data),]
plus<-data[complete.cases(data),]
plus

str(plus)
head(plus)
tail(plus)
class(plus$Date)
(plus[1:10, "^DJI.adjclose",drop=F])

#Create a new data frame that contains the price data with the dates as the row names
prices <- (plus)[, "^DJI.adjclose", drop = FALSE]
rownames(prices) <-plus$Date
head(prices)
tail(prices)

#to find the return from 3/3/2015-3/8/2018
djia_ret1<- ((prices [2:n,1]-prices [1:(n-1),1])/prices [1:(n-1),1])

1 个答案:

答案 0 :(得分:1)

  

2:n:NA / NaN参数出错。

这意味着:的两个参数中的一个(或两个)是NANaN2不是,n必须是。

在您的问题中,您没有展示如何创建变量n,但如果它是某些数据NA的结果,或者是除以结果的结果,那么导致这些错误。