thankgod
thankgod

Reputation: 21

Error in 2:n : NA/NaN argument

The code below produces the following error:

Error in 2:n : NA/NaN argument

How can I resolve this error?

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])

Upvotes: 2

Views: 28176

Answers (1)

JAD
JAD

Reputation: 2180

Error in 2:n : NA/NaN argument.

This means that one (or both) of the two arguments of : are NA or NaN. 2 is not, so n must be.

In your question you don't show how you created the variable n, but if it was the result of some data that was NA, or a division by zero result for example, that would cause these errors.

Upvotes: 2

Related Questions