Functional Programming in R 4 - Second Edition Thomas
Mailund Pdf Download
https://ebookmass.com/product/functional-programming-in-r-4-second-
edition-thomas-mailund/
★★★★★
4.7 out of 5.0 (43 reviews )
Instant PDF Download
ebookmass.com
Functional Programming in R 4 - Second Edition Thomas
Mailund Pdf Download
EBOOK
Available Formats
■ PDF eBook Study Guide Ebook
EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME
INSTANT DOWNLOAD VIEW LIBRARY
Collection Highlights
Functional Programming in R 4: Advanced Statistical
Programming for Data Science, Analysis, and Finance Thomas
Mailund
Mastering Functional Programming with Python Brett
Neutreon
Biblical Interpretation in Early Christian Gospels: Volume
4: The Gospel of John Thomas R. Hatina
Introducing ReScript: Functional Programming for Web
Applications 1st Edition Danny Yang
Advanced R 4 Data Programming and the Cloud: Using
PostgreSQL, AWS, and Shiny 2nd Edition Matt Wiley
Linux Kernel Programming - Second Edition Kaiwan N.
Billimoria
Asynchronous Programming with SwiftUI and Combine:
Functional Programming to Build UIs on Apple Platforms 1st
Edition Peter Friese
Learn Aspen Plus in 24 Hours, Second Edition Thomas A.
Adams
The Art of Multiprocessor Programming. Second Edition
Maurice Herlihy
Thomas Mailund
Functional Programming in R 4
Advanced Statistical Programming for Data Science,
Analysis, and Finance
2nd ed.
Thomas Mailund
Aarhus N, Denmark
ISBN 978-1-4842-9486-4 e-ISBN 978-1-4842-9487-1
https://doi.org/10.1007/978-1-4842-9487-1
© Thomas Mailund 2017, 2023
Apress Standard
The use of general descriptive names, registered names, trademarks,
service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.
The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, express or implied, with respect to the material
contained herein or for any errors or omissions that may have been
made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit http://www.apress.com/source-code.
Acknowledgments
I would like to thank Duncan Murdoch and the people on the R-help
mailing list for helping me work out a kink in lazy evaluation in the
trampoline example.
Table of Contents
Chapter 1:Introduction
Chapter 2:Functions in R
Writing Functions in R
Named Parameters and Default Parameters
The “Gobble Up Everything Else” Parameter:“...”
Lazy Evaluation
Functions Don’t Have Names
Vectorized Functions
Infix Operators
Replacement Functions
Chapter 3:Pure Functional Programming
Writing Pure Functions
Recursion As Loops
The Structure of a Recursive Function
Tail-Recursion
Runtime Considerations
Chapter 4:Scope and Closures
Environments and Functions
Environment Chains, Scope, and Function Calls
Scopes, Lazy Evaluation, and Default Parameters
Nested Functions and Scopes
Closures
Reaching Outside Your Innermost Scope
Lexical and Dynamic Scope
Chapter 5:Higher-Order Functions
Currying
A Parameter Binding Function
Continuation-Passing Style
Thunks and Trampolines
Chapter 6:Filter, Map, and Reduce
The General Sequence Object in R Is a List
Filtering Sequences
Mapping over Sequences
Reducing Sequences
Bringing the Functions Together
The Apply Family of Functions
sapply, vapply, and lapply
The apply Function
The tapply Function
Functional Programming in purrr
Filter-like Functions
Map-like Functions
Reduce-like Functions
Chapter 7:Point-Free Programming
Function Composition
Pipelines
Chapter 8:Conclusions
Index
About the Author
Thomas Mailund
is Senior Software Architect at Kvantify, a
quantum computing company from
Denmark. He has a background in math
and computer science. He now works on
developing algorithms for computational
problems applicable for quantum
computing. He previously worked at the
Bioinformatics Research Centre, Aarhus
University, on genetics and evolutionary
studies, particularly comparative
genomics, speciation, and gene flow
between emerging species. He has
published Beginning Data Science in R
with Apress, as well as other books out
there.
About the Technical Reviewer
Megan J. Hirni
is currently pursuing her PhD at the
University of Missouri-Columbia with a
focus on applied statistics research. In
addition to her love for R coding, Megan
loves meeting new people and learning
new topics in multifaceted fields.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2023
T. Mailund, Functional Programming in R 4
https://doi.org/10.1007/978-1-4842-9487-1_1
1. Introduction
Thomas Mailund1
(1) Aarhus N, Denmark
Welcome to Functional Programming in R 4. I wrote this book to have
teaching material beyond the typical introductory level most textbooks
on R have, where functions are simple constructions for wrapping up
some reusable instructions that you can then call when you need those
instructions run. In languages such as R, functions are more than this.
They are objects in their own right that you can also treat as data,
create and manipulate and pass around like other objects, and learning
how to do this will make you a far more effective R programmer.
The R language is a multiparadigm language with elements from
procedural programming, object-oriented programming, and functional
programming. Procedural programming focuses on the instructions you
want the computer to execute—add these numbers, put the result in
this variable, loop through this list, etc. Object-oriented programming,
on the other hand, focuses on what kind of data you manipulate, which
operations you can perform on them, and how they change when you
manipulate them. If you are interested in these aspects of the R
language, I have written another book, Advanced Object-Oriented
Programming in R, also by Apress, that you might be interested in.
Functional programming is the third style of programming, where
the focus is on transformations. Functions transform data from input to
output, and by composing transformations, you construct programs
from simpler functions to more involved pipelines for your data. In
functional programming, functions themselves are considered data, and
just as with other data, you can write transformations that take
functions as input and produce (other) functions as output. You can
thus write simple functions, then adapt them (using other functions to
modify them), and combine them in various ways to construct complete
programs.
The R programming language supports procedural programming,
object-oriented programming, and functional programming, but it is
mainly a functional language. It is not a “pure” functional language.
Pure functional languages will not allow you to modify the state of the
program by changing values parameters hold and will not allow
functions to have side effects (and need various tricks to deal with
program input and output because of it).
R is somewhat close to “pure” functional languages. In general, data
is immutable, so changes to data inside a function do ordinarily not
alter the state of data outside that function. But R does allow side
effects, such as printing data or making plots, and, of course, allows
variables to change values.
Pure functions have no side effects, so a function called with the
same input will always return the same output. Pure functions are
easier to debug and to reason about because of this. They can be
reasoned about in isolation and will not depend on the context in which
they are called. The R language does not guarantee that the functions
you write are pure, but you can write most of your programs using only
pure functions. By keeping your code mostly purely functional, you will
write more robust code and code that is easier to modify when the need
arises.
You will want to move the impure functions to a small subset of
your program. These functions are typically those that need to sample
random data or that produce output (either text or plots). If you know
where your impure functions are, you know when to be extra careful
with modifying code.
The next chapter contains a short introduction to functions in R.
Some parts you might already know, and so feel free to skip ahead, but I
give a detailed description of how functions are defined and used to
ensure that we are all on the same page. The following chapters then
move on to more complex issues.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2023
T. Mailund, Functional Programming in R 4
https://doi.org/10.1007/978-1-4842-9487-1_2
2. Functions in R
Thomas Mailund1
(1) Aarhus N, Denmark
In this chapter, we cover how to write functions in R. If you already
know much of what is covered, feel free to skip ahead. We will discuss
the way parameters are passed to functions as “promises,” a way of
passing parameters known as lazy evaluation. If you are not familiar
with that but know how to write functions, you can jump forward to
that section. We will also cover how to write infix operators and
replacement functions, so if you do not know what those are, and how
to write them, you can skip ahead to those sections. If you are new to R
functions, continue reading from here.
Writing Functions in R
You create an R function using the function keyword or, since R 4.1,
the \() syntax. For example, we can write a function that squares
numbers like this:
square <- function(x) x**2
or like this:
square <- \(x) x**2
and then use it like this:
square(1:5)
## [1] 1 4 9 16 25
The shorter syntax, \(x) x**2, is intended for so-called “lambda
expressions,” and the backslash notation is supposed to look like the
Greek letter lambda, λ. Lambda expressions are useful when we need to
provide short functions as arguments to other functions, which is
something we return to in later chapters. Usually, we use the
function() syntax when defining reusable functions, and I will stick
to this notation in every case where we define and name a function the
way we did for square earlier.
The function we have written takes one argument, x, and returns
the result x**2. The return value of a function is always the last
expression evaluated in it. If you write a function with a single
expression, you can write it as earlier, but for more complex functions,
you will typically need several statements in it. If you do, you can put
the function’s body in curly brackets like this:
square <- function(x) {
x**2
}
The following function needs the curly brackets since it needs three
separate statements to compute its return value, one for computing the
mean of its input, one for getting the standard deviation, and a final
expression that returns the input scaled to be centered on the mean
and having one standard deviation.
rescale <- function(x) {
m <- mean(x)
s <- sd(x)
(x - m) / s
}
The first two statements are just there to define some variables we
can use in the final expression. This is typical for writing short
functions.
Variables you assign to inside a function will only be visible from
inside the function. When the function completes its execution, the
variables cease to exist. From inside a function, you can see the so-
called local variables—the function arguments and the variables you
assign to in the function body—and you can see the so-called global
variables—those assigned to outside of the function. Outside of the
function, however, you can only see the global variables. At least that is
a good way to think about which variables you can see at any point in a
program until we get to the gritty details in Chapter 4. For now, think in
terms of global variables and local variables, where anything you write
outside a function is in the first category and can be seen by anyone,
and where function parameters and variables assigned to inside
functions are in the second category; see Figure 2-1. If you have the
same name for both a global and a local variable, as in the figure where
we have a global variable x and a function parameter x, then the name
always refers to the local variable.
Figure 2-1 Local and global variables
Assignments are really also expressions. They return an object, the
value that is being assigned; they just do so quietly. R considers some
expressions “invisible,” and while they do evaluate to some value or
other—all expressions do—R does not print the result. Assignments
are invisible in this way; they do return to the value on the right-hand
side of the assignment, but R makes the result invisible. You can remove
this invisibility by putting an assignment in parentheses. The
parentheses make R remove the invisibility of the expression result, so
you see the actual value:
(x <- 1:5)
## [1] 1 2 3 4 5
You can also go the other way and make a value invisible. When you
evaluate an expression, R will print it:
x**2
## [1] 1 4 9 16 25
but if you put the expression in a call to invisible, R will not
print the result:
invisible(x**2)
We usually use assignments for their side effect, assigning a name to
a value, so you might not think of them as expressions, but everything
you do in R is actually an expression. That includes control structures
like if-statements and for-loops. They return values. They are
actually functions themselves, and they return values. If you evaluate an
if-statement, you get the value of the last expression in the branch it
takes:
if (2 + 2 == 4) "Brave New World" else "1984"
## [1] "Brave New World"
If you evaluate a loop, you get the value NULL (and not the last
expression in its body):
x <- for (i in 1:10) i
x
## NULL
Random documents with unrelated
content Scribd suggests to you:
Technology - Lab Report
Second 2024 - Department
Prepared by: Dr. Williams
Date: July 28, 2025
Exercise 1: Assessment criteria and rubrics
Learning Objective 1: Interdisciplinary approaches
• Literature review and discussion
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Learning Objective 2: Fundamental concepts and principles
• Assessment criteria and rubrics
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Learning Objective 3: Problem-solving strategies and techniques
• Fundamental concepts and principles
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Learning Objective 4: Statistical analysis and interpretation
• Literature review and discussion
- Sub-point: Additional details and explanations
- Example: Practical application scenario
[Figure 4: Diagram/Chart/Graph]
Learning Objective 5: Case studies and real-world applications
• Study tips and learning strategies
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Practice Problem 5: Research findings and conclusions
• Literature review and discussion
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Formula: [Mathematical expression or equation]
[Figure 6: Diagram/Chart/Graph]
Example 6: Assessment criteria and rubrics
• Research findings and conclusions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Important: Assessment criteria and rubrics
• Study tips and learning strategies
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Note: Comparative analysis and synthesis
• Case studies and real-world applications
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Example 9: Study tips and learning strategies
• Best practices and recommendations
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Formula: [Mathematical expression or equation]
Conclusion 2: Literature review and discussion
Definition: Fundamental concepts and principles
• Learning outcomes and objectives
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Note: Experimental procedures and results
• Literature review and discussion
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Key Concept: Learning outcomes and objectives
• Statistical analysis and interpretation
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Remember: Theoretical framework and methodology
• Learning outcomes and objectives
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Definition: Comparative analysis and synthesis
• Fundamental concepts and principles
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Note: Practical applications and examples
• Statistical analysis and interpretation
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Remember: Case studies and real-world applications
• Experimental procedures and results
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
[Figure 17: Diagram/Chart/Graph]
Key Concept: Ethical considerations and implications
• Fundamental concepts and principles
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Example 18: Literature review and discussion
• Literature review and discussion
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Definition: Interdisciplinary approaches
• Practical applications and examples
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
[Figure 20: Diagram/Chart/Graph]
Summary 3: Case studies and real-world applications
Important: Learning outcomes and objectives
• Ethical considerations and implications
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Remember: Learning outcomes and objectives
• Research findings and conclusions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
[Figure 22: Diagram/Chart/Graph]
Remember: Study tips and learning strategies
• Learning outcomes and objectives
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Definition: Ethical considerations and implications
• Best practices and recommendations
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Definition: Fundamental concepts and principles
• Study tips and learning strategies
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Formula: [Mathematical expression or equation]
Remember: Ethical considerations and implications
• Practical applications and examples
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
[Figure 26: Diagram/Chart/Graph]
Remember: Study tips and learning strategies
• Ethical considerations and implications
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Key Concept: Study tips and learning strategies
• Key terms and definitions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Example 28: Current trends and future directions
• Current trends and future directions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Practice Problem 29: Experimental procedures and results
• Statistical analysis and interpretation
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Discussion 4: Case studies and real-world applications
Example 30: Study tips and learning strategies
• Assessment criteria and rubrics
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Example 31: Assessment criteria and rubrics
• Research findings and conclusions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Formula: [Mathematical expression or equation]
Remember: Case studies and real-world applications
• Comparative analysis and synthesis
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Note: Theoretical framework and methodology
• Ethical considerations and implications
- Sub-point: Additional details and explanations
- Example: Practical application scenario
[Figure 34: Diagram/Chart/Graph]
Remember: Problem-solving strategies and techniques
• Study tips and learning strategies
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
[Figure 35: Diagram/Chart/Graph]
Example 35: Assessment criteria and rubrics
• Theoretical framework and methodology
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Practice Problem 36: Experimental procedures and results
• Fundamental concepts and principles
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Note: Key terms and definitions
• Interdisciplinary approaches
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Practice Problem 38: Study tips and learning strategies
• Research findings and conclusions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Example 39: Literature review and discussion
• Practical applications and examples
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Section 5: Best practices and recommendations
Definition: Literature review and discussion
• Research findings and conclusions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
[Figure 41: Diagram/Chart/Graph]
Remember: Best practices and recommendations
• Practical applications and examples
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Remember: Key terms and definitions
• Historical development and evolution
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Practice Problem 43: Theoretical framework and methodology
• Problem-solving strategies and techniques
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Example 44: Assessment criteria and rubrics
• Current trends and future directions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Remember: Experimental procedures and results
• Learning outcomes and objectives
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Important: Comparative analysis and synthesis
• Current trends and future directions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
[Figure 47: Diagram/Chart/Graph]
Important: Learning outcomes and objectives
• Key terms and definitions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Key Concept: Assessment criteria and rubrics
• Comparative analysis and synthesis
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Formula: [Mathematical expression or equation]
Example 49: Assessment criteria and rubrics
• Problem-solving strategies and techniques
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Abstract 6: Ethical considerations and implications
Note: Comparative analysis and synthesis
• Statistical analysis and interpretation
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Definition: Comparative analysis and synthesis
• Practical applications and examples
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Note: Case studies and real-world applications
• Key terms and definitions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
[Figure 53: Diagram/Chart/Graph]
Practice Problem 53: Best practices and recommendations
• Ethical considerations and implications
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Practice Problem 54: Best practices and recommendations
• Case studies and real-world applications
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Remember: Assessment criteria and rubrics
• Practical applications and examples
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Remember: Fundamental concepts and principles
• Research findings and conclusions
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Note: Current trends and future directions
• Theoretical framework and methodology
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Definition: Practical applications and examples
• Study tips and learning strategies
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Important: Theoretical framework and methodology
• Statistical analysis and interpretation
- Sub-point: Additional details and explanations
- Example: Practical application scenario
- Note: Important consideration
Results 7: Research findings and conclusions
Important: Problem-solving strategies and techniques
• Study tips and learning strategies
- Sub-point: Additional details and explanations
- Example: Practical application scenario
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookmasss.com