Common R code snippets
Anything and everything that can be automated should be automated.
This thought motivated me to look deeply into my daily coding that I do. Am I repeating some code snippets that I can improve upon? Can I write these common codes into functions so that I can use them repeatedly without repeating the effort?
And then I started writing these repeatable codes into small code snippets and now I just call these functions and use them in my work. I mostly work on R and I will be sharing my code snippets as and when I write them.
Loading a package in R
Every time we need to use some functions which are not in the base R package, we have to load that package in R. Now two cases are possible:
You have the package (say ‘forecast’) already installed in R and you just need to include it in R using library()
library(forecast)
Or
You don’t have the package installed so you first install it and then include it in R.
install.packages(‘forecast’, dependencies=T)
What if you have multiple packages to install? So every time you will have to install each package and include them in R. The following paragraph will explain how to write a function which takes care of the two cases easily.
installed.packages()[,1]
Gives you the list of all packages that you have already installed in R
The following function, loadPackages will help you solve the issue and save time.
loadPackages <- function(packages) {
for (package in packages) {
isInstalled <- is.element(package, installed.packages()[,1])
if(!isInstalled) {
try(install.packages(package), silent = T)
}
cat(package, “\n”)
try(library(package, character.only = T), silent = T)
}
}That’s all for now. I will break down and explain each part of the code next time.