TEST NOT WORKING PROPERLY

As we have seen, R comes with many useful functions, and still more functions are available by way of R libraries. However, we will often be interested in performing an operation for which no function is available. In this setting, we may want to write our own function. For instance, below we provide a simple function that reads in the ISLR2 and MASS libraries, called LoadLibraries(). Before we have created the function, R returns an error if we try to call it.

> LoadLibraries
Error: object ’LoadLibraries ’ not found
> LoadLibraries()
Error: could not find function " LoadLibraries"

We now create the function. Note that the + symbols are printed by R and should not be typed in. The { symbol informs R that multiple commands are about to be input. Hitting Enter after typing { will cause R to print the + symbol. We can then input as many commands as we wish, hitting Enter after each one. Finally the } symbol informs R that no further commands will be entered.

> LoadLibraries <- function() {
+     library(ISLR2)
+     library(MASS)
+     print("The libraries have been loaded.")
+ }

Now if we type in LoadLibraries, R will tell us what is in the function.

LoadLibraries
function (){
    library(ISLR2)
    library(MASS)
    print("The libraries have been loaded.")
}

If we want to actually use the function, we add parentheses. Our function does not require any argument, so we don’t need to specify anything inside the parentheses. Now that we called the function, the libraries are loaded and the print statement is output.

> LoadLibraries()
[1] "The libraries have been loaded."

Try augmenting the function by also loading one of the datasets we use frequently: ‘Boston’.