aflindst
aflindst

Reputation: 23

Count the frequency of functions written in my R script files?

I would like to tabulate how often a function is used in one or more R script files. I have found the function NCmisc::list.functions.in.file, and it is very close to what I want:

library(stringr)
cat("median(iris$Sepal.Length)\n  median(iris$Sepal.Width)\n library(stringr); str_length(iris$Species) \n", file = "script.R")
list.functions.in.file("script.R")

   package:base   package:stats package:stringr 
      "library"        "median"    "str_length" 

Note that median is used twice in the script, but list.functions.in.file does not use this information, and only lists each unique function. Are there any packages out there that can produce such frequencies? And bonus for the ability to analyze a corpus of multiple R scripts, not just a single file.

(note this is NOT about counting function calls, e.g. in recursion, and I want to avoid executing the scripts)

Upvotes: 2

Views: 231

Answers (1)

tim_yates
tim_yates

Reputation: 171154

That NCmisc function is just a wrapper round utils::parse and utils::getParseData, so you can just make your own function (and then you don't need the dependency on NCmisc:

count.function.names <- function(file) {
  data <- getParseData(parse(file=file))
  function_names <- data$text[which(data$token=="SYMBOL_FUNCTION_CALL")]
  occurrences <- data.frame(table(function_names))
  result <- occurrences$Freq
  names(result) <- occurrences$function_names
  result
}

Should do what you want...

Upvotes: 4

Related Questions