R - How to do Python's Try Except

I'm starting to work with R. Although I'm more used to python.

I want to do a script in R that uses the library MASS. I though about doing a Try, Except to see if the library exists, otherwise install it. Something like this:

Try:
    library("MASS")
Except SomeError:
    install.packages("MASS")
    library("MASS")

Or perhaps in R this doesn't make much sense. Anyway any suggestions is welcome :)

Answers


The function require is virtually identical to library, except it returns a logical value.

> x <- require("MASS")
> x
[1] TRUE

> x <- require("notExist")
Loading required package: notExist
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'notExist'
> x
[1] FALSE

This means you can use a simple if statement, something like:

if(!require("MASS")) install.packages("MASS")

R also has an error capturing mechanism. Read about it at ?try or ?tryCatch


Need Your Help

Unexpected CFBundleExecutable key

ios itunesconnect cocoapods ios9 xcode7-beta5

After spending some time googling, something tells me that the issue is new.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.