CHAPTER 07
Beginner
Functions in R
Updated: May 18, 2026
5 min read
# CHAPTER 7
Functions in R
1. Chapter Introduction
Functions are the core unit of reusability in R. This chapter covers function creation, argument handling, return values, anonymous functions, closures, and the apply family — the tools that make R programs clean, modular, and fast.2. Creating Functions
r
3. Variable Arguments with ...
r
4. Anonymous Functions
r
5. Apply Family
r
6. Common Mistakes
-
Modifying global variables inside functions: R uses lexical scoping with copy-on-modify. Functions get copies of arguments; use
<<-only when you truly need global side effects (rare).
-
Forgetting
return()in complex conditionals: R returns the last evaluated expression — but in if/else branches, this can be surprising. Use explicitreturn()in functions with multiple exit paths.
7. MCQs
Question 1
R function implicit return is?
Question 2
Default argument f(x, n=10) can be overridden by?
Question 3
... (ellipsis) in function arguments?
Question 4
sapply() returns?
Question 5
tapply(x, group, FUN) applies FUN?
Question 6
\(x) x^2 in R 4.1+ is?
Question 7
Multiple return values in R use?
Question 8
stopifnot() is for?
Question 9
mapply(FUN, ...) applies FUN?
Question 10
Lexical scoping in R means?
8. Interview Questions
-
Q: What is the difference between
sapply(),lapply(), andvapply()?
- Q: What is a closure in R?
9. Summary
Functions in R:function(args) { body }, implicit last-expression return. Default args with arg=value. Variable args with .... Multiple returns via list. Apply family: sapply() (simplify), lapply() (list), apply() (margins), tapply() (groups), mapply() (multivariate). R 4.1+ anonymous shorthand: \(x). Use stopifnot() for validation. R uses lexical scoping — functions see variables from where they were defined.