Skip to contents

Dispatches to a method based on the type of input (function, expression, or character). Writes a valid R function definition to a .R file, assigning it the provided or inferred name.

Usage

save_function_to_file(fn, fn_name, file, ...)

# S3 method for class '`function`'
save_function_to_file(fn, fn_name = NULL, file = NULL, ...)

# S3 method for class 'expression'
save_function_to_file(fn, fn_name, file = NULL, ...)

# S3 method for class 'character'
save_function_to_file(fn, fn_name, file = NULL, ...)

Arguments

fn

The function code to save. Can be a function object, an expression() containing a function, or a character string with valid R function code.

fn_name

Required name to assign the function in the output file.

file

Optional file name to write to. Defaults to <fn_name>.R.

...

Passed to class-specific methods.

Value

Invisibly returns the normalized file path.

Details

The expression must contain a function definition, such as expression(function(x) x^2). If this structure is not detected, an error is raised.

The expression must contain a function definition, such as expression(function(x) x^2). If this structure is not detected, an error is raised.

The string must parse as valid R code starting with function(...). This method is useful when saving LLM-generated code or string-encoded snippets that define a function.

Methods (by class)

  • save_function_to_file(`function`): Save a function defined as an expression

  • save_function_to_file(expression): Save a function defined as an expression

  • save_function_to_file(character): Save a function from a character string

Examples

if (FALSE) { # \dontrun{
save_function_to_file(expression(function(x) x^2), fn_name = "square")
} # }

if (FALSE) { # \dontrun{
save_function_to_file(expression(function(x) x^2), fn_name = "square")
} # }

if (FALSE) { # \dontrun{
save_function_to_file("function(x) log(x + 1)", fn_name = "logplus1")
} # }