write a function that accepts a path to a r script and returns the paths declared there in r

main.r
extract_paths_from_r_script <- function(path_to_script) {
  # read in the lines of the R script
  script_lines <- readLines(path_to_script)
  
  # extract paths from declarations
  declared_paths <- grep("^\\s*[a-zA-Z]+ <-", script_lines, value = TRUE)
  extracted_paths <- sub("^\\s*[a-zA-Z]+ <-\\s*\"(.+)\".*", "\\1", declared_paths)
  
  return(extracted_paths)
}
367 chars
11 lines

This function takes as input a path_to_script variable that must contain a string path to the R script to extract the path declarations from. The readLines function is used to read in all of the lines of the script into a character vector.

Then, the grep function is used to extract only the lines that declare a path, and the sub function is used to extract the path itself from each of these lines.

Finally, the extracted paths are returned as a character vector.

gistlibby LogSnag