Skip to contents

This function refactors R code with the assistance of an AI chatbot.

Usage

refactor(file, ..., overwrite = FALSE)

Arguments

file

character, file name of a file containing R code to be refactored or a character string containing R code to be refactored

...

Additional arguments to pass to the chat_completion() function.

overwrite

Logical. If FALSE (default), the function stops before calling the API when the output file (<name>_refactored.<ext>) already exists; if TRUE, it replaces it. Only used for file input. The input file itself is never modified.

Value

For literal text or a URL: the refactored code as a character string, returned visibly; nothing is written. For a file name: the path of the file it was written to, returned invisibly. File output goes to a new file next to the input, <name>_refactored.<ext>, which contains only the refactored code; the input file is left untouched. Input that does not parse as R stops before any API call, as does empty input (error class openair_empty_input). For file input, output that does not parse as R is not written: the function stops with an error of class openair_invalid_output whose output field holds the code. Literal or URL input returns such output all the same, with a message that it may be invalid.

Examples

if (FALSE) { # \dontrun{
# Create a sample R function file in the temporary directory
f <- tempfile(fileext = ".R")
cat("my_sum <- function(a, b) {", "return(a + b)", "}",
 file = f, sep = "\n")

# A file: the refactored code is written to <name>_refactored.R next to
# it, whose path is returned invisibly
out_file <- refactor(file = f)
cat(readLines(out_file), sep = "\n")
unlink(c(f, out_file))

# A character string: the refactored code is returned
refactored_function <- refactor("my_sum <- function(a, b) { return(a + b) }")
} # }