7. Functions - JulTob/R GitHub Wiki

⚓ Chart of Functions

“A function be a named spell: cast it with arguments, and it returns its treasure.”

In R, ye define a function with the function() constructor and call it by name. This chart covers the basics: defining, overwriting, copying, and editing functions.

🪝 Defining a Simple Function

Let’s define the function for f(x) = 2x:

> f <- function(x) {
    2 * x
}
> f(4)
[1] 8

Functions can take arguments, perform operations, and return a result (automatically, unless ye use return()).

🧪 Using Variables Inside

> a <- 2
> f(a)
[1] 4

Functions work with variables as long as their names be known in the current environment.

🔁 Overwriting a Function

Assignin’ something new to a name replaces the old object.

> f <- function(x) { 2 * x }
> f(3)
[1] 6

> f <- function(x) { x * x }
> f(3)
[1] 9

⚠️ The old version is gone unless ye saved it elsewhere!

💾 Backin’ Up a Function

If ye want to keep the original before overwriting it, make a copy:

> f <- function(x) { x * x }
> nuevaf <- f

> f <- function(x) { 2 * x }

> nuevaf(3)
[1] 9
> f(3)
[1] 6

📝 Editing a Function

Use fix() or edit() to pop open a tiny editor window:

> fix(f)
  • This lets ye modify an existing function.
  • Works best in RStudio with syntax highlighting.
  • Be warned: fix() edits the function in-place.

🔍 See a Function’s Definition

> f
function(x) {
  2 * x
}

If it be a base function, ye might see:

> sum
function (..., na.rm = FALSE)  .Primitive("sum")

Some built-ins are too low-level to view directly.

⚓ Summary of Function Essentials

Task Code Example
Define a function f <- function(x) { x + 1 }
Call a function f(4)
Overwrite a function f <- function(x) { x^2 }
Copy a function backup <- f
Edit a function fix(f)
View code of a function f