How can I count the lines of code in an R package? I have two possible types of input:
In either case, I specifically want the number of lines of code while skipping comment lines and blank lines. I don't need the number of comment lines, but if the function provides these, that would be fine. A function that counts these lines as a secondary function might also be good, as long as the secondary function does not take too much time.
I prefer an R function (run from within R) rather than a command line or terminal command (run from outside R). The function must recognize R comments.
We can start developing something from
1) With readLines()
count = \(p) {
l = readLines(p) # warn=FALSE
length(l[!grepl('^\\s*(#.*)?$', l)])
}
readLines()
might through warning(s)
In readLines(p) : incomplete final line found on './blahblah.R'
This should be due to missing End Of Line (EOL) and can be ignored.
2) With scan()
count2 = \(p) {
l = scan(p, what='', sep='\n', blank.lines.skip=TRUE)
length(l[!grepl('^\\s*#', l)])
}
Apply
r = list.files(path='>top_level_folder<', pattern='.R$', full.names=TRUE, recursive=TRUE)
sum(sapply(r, count))
sum(sapply(r, count2))
As User @SamR points out in a comment below this answer, there is {cloc}
. You might want to check it out.