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 :)
The function require is virtually identical to library, except it returns a logical value.
> x <- require("MASS") > x  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  FALSE
This means you can use a simple if statement, something like:
R also has an error capturing mechanism. Read about it at ?try or ?tryCatch