# Functions

## 1. Defining and calling a function ----------------------------------
```{r}
# function 
greet <- function(name) {
  paste("Hello,", name)
}

# function call 
greet("World")
# [1] "Hello, World"
```

## 2. Return values ----------------------------------------------------
R returns the LAST expression evaluated. 
`return()` is only needed for early exits.
```{r}
# function 
square <- function(x) {
  x * x        # this value is returned
}

# function call
square(5)      # 25
```

### 2.1 Early exit example
```{r}
# function 
abs_value <- function(x) {
  if (x < 0) return(-x)
  x
}
 
# function call
abs_value(-7)  # 7 # early return
abs_value(3)   # 3 # returns the last expression evaluated
```

## 3. Default arguments & named arguments ------------------------------
```{r}
# function 
greet2 <- function(name = "World", greeting = "Hello") {
  paste0(greeting, ", ", name, "!")
}
 
# function calls
greet2()                                # "Hello, world!"  # default
greet2("Alice")                         # "Hello, Alice!"  # override name
greet2(greeting = "Hi", name = "Bob")   # "Hi, Bob!"       # override all params
```

## 4. Returning multiple values via a list -----------------------------
```{r}
# function 
stats <- function(x) {
  list(
    mean = mean(x),
    sd   = sd(x),
    n    = length(x)
  )
}

# function calls
result <- stats(c(1, 2, 3, 4, 5))
result
result$mean   # 3
result$sd     # 1.581139
result$n      # 5
```
 
## 5. Vectorized by default --------------------------------------------
Most R functions operate on whole vectors at once — no loop needed.
```{r}
# function 
add_one <- function(x) x + 1

# function call
add_one(c(10, 20, 30))   # 11 21 31
```
 
## 6. Anonymous functions ----------------------------------------------
Useful inside sapply / lapply / purrr::map etc.
```{r}
# function: anonymous: inside sapply
sapply(1:5, function(x) x^2)   # 1  4  9 16 25
# function: anonymous: inside sapply: R 4.1+ shorthand
sapply(1:5, \(x) x^2)          # same thing
```

## 7. The ... (dots) argument ------------------------------------------
Pass arbitrary extra arguments through to another function.
```{r}
# function
my_summary <- function(x, ...) {
  # forward extras to round()
  round(mean(x), ...)
}

# function calls
my_summary(c(1.234, 5.678, 9.1011))             # 5
my_summary(c(1.234, 5.678, 9.1011), digits = 2) # 5.34
```

## 8. Putting it together ----------------------------------------------
# function
```{r}
describe <- function(x, label = "values") {
  s <- stats(x)
  cat("Summary of", label, "\n")
  cat("  n    =", s$n, "\n")
  cat("  mean =", round(s$mean, 3), "\n")
  cat("  sd   =", round(s$sd, 3), "\n")
  invisible(s)   # returns the list silently
}
# function call
describe(rnorm(100), label = "100 random normals")
```
How do functions work in R?

Copy + Paste 
the code on the left
into any .Rmd file

Ctrl + Enter
each line from the top down
See the output
Understand