Whether you use R to access online databases in the cloud or want to scrape website data, it’s always better to check if you are online before throwing numerous error and warning messages. I wrote this function to work with no additional R packages required. Also, this function is fast and transparent about what occurs when you use it.

This function was developed and validated on R 3.1.2 in a Windows 8.1 environment. Enjoy!

######################################################################
#       Script: R online test.R 
#       Author: Stephen McDaniel 
# Organization: Freakalytics, LLC
# Date created: 2015/02/22
#     Mod date: N/A
#    Copyright: (C) 2015 by Freakalytics, LLC
#      License: The MIT License at http://opensource.org/licenses/MIT
#
########## About this code
# The function online_test is useful for checking if you are online 
#   using just base R (no additional packages required) 
# To minimize run time, only one ping request is made by this function 
#
# To use this in any of your scripts, add just the function 
#   portion of this script to .Rprofile (typically in Documents
#   directory on Windows PCs)
#
########## Input
# The only input required is the site or IP address that you consider
#   reliable or relevant for checking if you are "online"
#
########## Sample returned values
# TRUE or FALSE
#
######################################################################

online_test <- function(web_address) {
  (tryCatch(system(paste0("ping -n 1 ", web_address), 
      intern=TRUE),
      error = function(c) "0",
      warning = function(c) "0",
      message = function(c) "0"
  ) != 0 )[1]
}

# Should return FALSE, whether or not online 
online_test("yahooooooo.com")
# Should return TRUE when online
online_test("yahoo.com")

# An example of using this function 
if(online_test( "yahoo.com" )) { 
  cat("Online now, running your cool code!")
  # connect to your online resources 
} else {
  cat("Sorry, you aren't online!")
  # Other alternate code or just take a break
}

Next Post