Reputation: 207
I would like to know if there is a way to count the number of lines in a R script.
Ignoring lines of comment.
I didn't find a solution on the Internet. But maybe I missed something.
Upvotes: 1
Views: 1502
Reputation: 1321
Example sctipt tester.R
with 8 lines, one commented:
x <- 3
x+1
x+2
#x+4
x*x
Function to count lines without comments:
foo <- function(path) {
rln <- read_lines(path)
rln <- rln[-grep(x = trimws(rln) , pattern = '^#')]
rln <- rln[ trimws(rln) != '']
return(length(rln))
}
Test run:
> foo('tester.R')
[1] 7
Upvotes: 2
Reputation: 341
You could try this :
library(magrittr)
library(stringr)
library(readr)
number_of_lines_of_code <- function(file_path){
file <- readr::read_file(file_path)
file_lines <- file %>% stringr::str_split("\n")
first_character_of_lines <- file_lines %>%
lapply(function(line)stringr::str_replace_all(line," ","")) %>%
lapply(function(line)stringr::str_sub(line,1,1)) %>%
unlist
sum(first_character_of_lines != "#" & first_character_of_lines != "\r")
}
number_of_lines_of_code("your/file/path.R")
Upvotes: 2
Reputation: 132969
That doesn't seem like very useful information, but you can do this:
script <- "#assign
a <- 1
b <- 2
"
nrow(read.table(text = script, sep = "°"))
[1] 2
I use °
as the separator, because it's an unlikely character in most R scripts. Adjust that as needed.
Of course, this could be done much more efficiently outside of R.
Upvotes: -1