R Code Quality
Code quality in R
Recall that style guides help make code easier to read, share, and verify. There are tools that can help us perform this activity.
Two ways to perform this in R are:
- Enable Diagnostics in RStudio
LintR package in R
The LintR package in R, will act as a static code analyzer. It checks adherence to a given style, syntax errors and possible semantic issues. Most of the default linters in this package are based on Hadley Wickham's R Style Guide lintr has the following methods
To execute the lintr command, use lint(“path of R script”) and run.
The below example considers that the R script is saved as ‘testSyntax.r’ in d:/R/ location.
CODE/PROGRAM/EXAMPLE
readFile = read.csv("D:/R/file.csv")
hello.world = c("Learn", "R", "Programming")
greater.1000 <- function(x){
if (x > 1000){
print("the number is greater than 1000")
}
else {
print("the number is less than or equal to 1000")
}
}
#Command to execute the R script
#lint("Path of the R file location")
setwd("D:/R/")
lint("testSyntax.r")
The output of lint() function
We can observe style errors for the given script in the console. Double clicking on the error in the console will take us to the line where the error is observed.
CODE/PROGRAM/EXAMPLE
#lint("Path of the R file location")
setwd("D:/R/")
lint("testSyntax.r")
Output:
Enabling diagnostics in RStudio
The second method is, by enabling diagnostics in R Studio. This feature was introduced in v0.99.
It can be accessed from:
R Studio >> Tools >> Global Options >> Code >> Diagnostics
Once there, select all the options in R Diagnostics.
Once the options are enabled, while writing the code, we can observe that the R Studio will aid us in correcting the style errors by providing the comments.