Skip to content

Instantly share code, notes, and snippets.

@joshua-feldman
Last active February 11, 2024 13:24
Show Gist options
  • Save joshua-feldman/3b3531b660e8434564ecbd02816748e6 to your computer and use it in GitHub Desktop.
Save joshua-feldman/3b3531b660e8434564ecbd02816748e6 to your computer and use it in GitHub Desktop.
Prepend all functions in an R script with package name
# Load the relevant packages
library(NCmisc)
library(stringr)
# Load the script and parse lines
file_name <- "example_script.R"
file_lines <- readLines(file_name)
# Save the function and package names
functions_list <- list.functions.in.file(file_name)
names(functions_list) <- paste(str_remove(names(functions_list), "package:"), "::", sep = "")
# Initialise new file
new_file <- file_lines
# Exclude lines with comments or package loads
indices <- which(str_detect(new_file, "#|library"))
new_file[indices] <- ""
# Create nested loop to prepend each function with package name
for(i in 1:length(functions_list)) {
for(j in 1:length(functions_list[[i]])) {
new_file <<- str_replace_all(new_file,
functions_list[[i]][j],
paste(names(functions_list)[i], functions_list[[i]][j], sep = ""))
}
}
# Replace lines with comments or package loads
new_file[indices] <- file_lines[indices]
# Overwrite the old file
cat(new_file, file = file_name, sep = "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment