1

Hello I am trying to skip over some Error messages and continue with the loop by writing an empty csv to my working d directory.

############################## 

Friday <- Sys.Date()-3

# Get Previous 4 days
Thursday <- Friday - 1
Wednesday <- Thursday -1
Tuesday <- Wednesday -1
Monday <- Tuesday -1

# format dates for loop
Friday <- format(Friday, "%Y%m%d")
Thursday<- format(Thursday, "%Y%m%d")
Wednesday<- format(Wednesday, "%Y%m%d")
Tuesday<- format(Tuesday, "%Y%m%d")
Monday<-format(Monday, "%Y%m%d")

# STOCKs to pull
stock1 <- c ("SPY.A","PCMI.O", "AMZN.O") # should generate error on 2nd occurance

# create function to retrieve data
pull = function (stock1){

AAPLFRI<- read.delim(header=TRUE, stringsAsFactor=FALSE,
                   paste(sep="",
                         "http://hopey.netfonds.no/tradedump.php?date=",
                         Friday,"&paper=",stock1,"&csv_format=txt"))

AAPLTHURS <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                      paste(sep="",
                            "http://hopey.netfonds.no/tradedump.php?date=",
                            Thursday,"&paper=",stock1,"&csv_format=txt"))

AAPLWED <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                    paste(sep="",
                          "http://hopey.netfonds.no/tradedump.php?date=",
                          Wednesday,"&paper=",stock1,"&csv_format=txt"))

AAPLTUES <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                     paste(sep="",
                           "http://hopey.netfonds.no/tradedump.php?date=",
                           Tuesday,"&paper=",stock1,"&csv_format=txt"))

AAPLMON <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                    paste(sep="",
                          "http://hopey.netfonds.no/tradedump.php?date=",
                          Monday,"&paper=",stock1,"&csv_format=txt"))

#Eliminate unwanted Columns in Data
AAPLMON <- AAPLMON[,c(1:3)]
AAPLTUES <- AAPLTUES[,c(1:3)]
AAPLWED <- AAPLWED[,c(1:3)]
AAPLTHURS <- AAPLTHURS[,c(1:3)]
AAPLFRI <- AAPLFRI[,c(1:3)]


# Try to skip over errors when binding data

if (is.error(rbind(AAPLMON,AAPLTUES,AAPLWED, AAPLTHURS, AAPLFRI ))){

SERIES <- 1

}

SERIES <- rbind(AAPLMON,AAPLTUES,AAPLWED, AAPLTHURS, AAPLFRI )

#Write .CSV File
write.csv(SERIES,paste(sep="",stock1,"_",Friday,".csv"))

}

# Use Apply to repeat through "stock1" 
apply(t(stock1), 2, pull)-> listo

The problem is that there is no is.error() that I know of? and I am not sure how to implement the try() wrapper to get the desired outcome.

Rime
  • 912
  • 2
  • 11
  • 39

1 Answers1

3
tryit <- try(rbind(AAPLMON,AAPLTUES,AAPLWED, AAPLTHURS, AAPLFRI ))

if(inherits(tryit, "try-error")){
    # do something when error
} else {
    # do something when no error
}
Remko Duursma
  • 2,741
  • 17
  • 24