R Functions

Defining a Function

This creates a function named myFunction with no parameters.

myFunction <- function() {
  print("Hello from a function!")
}

Calling a Function

Invokes the function and runs the code inside.

myFunction()

Parameters and Arguments

You can pass arguments or use default values if omitted.

Loading...
Output:

Return Values

return() sends back a result. If omitted, the last line is returned.

Loading...
Output:

Scope

x <- 10

test <- function() {
  x <- 5
  print(x)
}

test()   # prints 5
print(x) # prints 10

Local variables inside a function do not affect global variables unless <<- is used.

Anonymous Functions

lapply(1:5, function(x) x^2)

Used for short, one-off operations inside other functions.

Best Practices

  • Keep functions modular and reusable
  • Use default parameters for flexibility
  • Avoid modifying global variables from within functions

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic