'Re-run the execution if API call fails in R

I have the following API call function:

 df.load <- loaddf(r = as.character(readline(prompt = "Please enter r parameter: "))
                                  ,y= as.character(readline(prompt = "Please enter y parameter: "))
                                  ,z= as.character(readline(prompt = "Please enter z parameter: ")) )
                                  ,format="json"
    
    

# Convert to dataframe
data.df <- as.data.frame(df.load )

However, sometimes it fails to connect:

Warning in file(file, "rt") :
  InternetOpenUrl failed: 'A connection with the server could not be established'
Error in file(file, "rt") : cannot open the connection

and a number of observations in the final dataframe data.df is equal to 0, but when I re-run the code 3-4 times, it works.

Therefore I want to push R to re-run this chunk in the .rmd file if the connection failed or a number of observations are equal to 0 in data.df. Or if you have any other ideas on how to solve this issue I am open to your suggestions.

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source