Functional Programming in R 4 Advanced Statistical Programming For Data Science Analysis and Finance Thomas Mailund Full Chapter

Вам также может понравиться

Скачать как pdf или txt
Скачать как pdf или txt
Вы находитесь на странице: 1из 52

Functional Programming in R 4:

Advanced Statistical Programming for


Data Science, Analysis, and Finance
Thomas Mailund
Visit to download the full and correct content document:
https://ebookmass.com/product/functional-programming-in-r-4-advanced-statistical-pr
ogramming-for-data-science-analysis-and-finance-thomas-mailund/
Functional
Programming in R 4
Advanced Statistical
Programming for Data Science,
Analysis, and Finance
Second Edition

Thomas Mailund
Functional Programming in R 4: Advanced Statistical Programming for
Data Science, Analysis, and Finance

Thomas Mailund
Aarhus N, Denmark

ISBN-13 (pbk): 978-1-4842-9486-4 ISBN-13 (electronic): 978-1-4842-9487-1


https://doi.org/10.1007/978-1-4842-9487-1
Copyright © 2023 by Thomas Mailund
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Melissa Duffy
Development Editor: James Markham
Editorial Project Manager: Mark Powers
Cover designed by eStudioCalamar
Cover image by Max van den Oetelaar on Unsplash (www.unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY
10004, U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com,
or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance
Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for
reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
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.
Printed on acid-free paper
Table of Contents
About the Author��������������������������������������������������������������������������������vii

About the Technical Reviewer�������������������������������������������������������������ix

Acknowledgments�������������������������������������������������������������������������������xi

Chapter 1: Introduction������������������������������������������������������������������������1

Chapter 2: Functions in R���������������������������������������������������������������������3


Writing Functions in R�������������������������������������������������������������������������������������������3
Named Parameters and Default Parameters��������������������������������������������������������9
The “Gobble Up Everything Else” Parameter: “...”�����������������������������������������������10
Lazy Evaluation���������������������������������������������������������������������������������������������������13
Functions Don’t Have Names������������������������������������������������������������������������������20
Vectorized Functions�������������������������������������������������������������������������������������������21
Infix Operators����������������������������������������������������������������������������������������������������27
Replacement Functions��������������������������������������������������������������������������������������31

Chapter 3: Pure Functional Programming������������������������������������������41


Writing Pure Functions����������������������������������������������������������������������������������������42
Recursion As Loops���������������������������������������������������������������������������������������������44
The Structure of a Recursive Function����������������������������������������������������������������49
Tail-Recursion�����������������������������������������������������������������������������������������������������58
Runtime Considerations��������������������������������������������������������������������������������������60

iii
Table of Contents

Chapter 4: Scope and Closures�����������������������������������������������������������65


Environments and Functions������������������������������������������������������������������������������68
Environment Chains, Scope, and Function Calls�������������������������������������������������71
Scopes, Lazy Evaluation, and Default Parameters����������������������������������������������74
Nested Functions and Scopes�����������������������������������������������������������������������������78
Closures��������������������������������������������������������������������������������������������������������������84
Reaching Outside Your Innermost Scope������������������������������������������������������������86
Lexical and Dynamic Scope��������������������������������������������������������������������������������90

Chapter 5: Higher-Order Functions�����������������������������������������������������93


Currying��������������������������������������������������������������������������������������������������������������96
A Parameter Binding Function��������������������������������������������������������������������������103
Continuation-Passing Style�������������������������������������������������������������������������������105
Thunks and Trampolines�����������������������������������������������������������������������������������111

Chapter 6: Filter, Map, and Reduce���������������������������������������������������119


The General Sequence Object in R Is a List������������������������������������������������������120
Filtering Sequences������������������������������������������������������������������������������������������122
Mapping over Sequences����������������������������������������������������������������������������������124
Reducing Sequences����������������������������������������������������������������������������������������127
Bringing the Functions Together�����������������������������������������������������������������������130
The Apply Family of Functions��������������������������������������������������������������������������134
sapply, vapply, and lapply����������������������������������������������������������������������������������134
The apply Function��������������������������������������������������������������������������������������������136
The tapply Function������������������������������������������������������������������������������������������137
Functional Programming in purrr����������������������������������������������������������������������138
Filter-like Functions������������������������������������������������������������������������������������������139

iv
Table of Contents

Map-like Functions�������������������������������������������������������������������������������������������141
Reduce-like Functions��������������������������������������������������������������������������������������144

Chapter 7: Point-Free Programming�������������������������������������������������145


Function Composition���������������������������������������������������������������������������������������146
Pipelines�����������������������������������������������������������������������������������������������������������148

Chapter 8: Conclusions���������������������������������������������������������������������153

Index�������������������������������������������������������������������������������������������������155

v
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.

vii
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.

ix
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.

xi
CHAPTER 1

Introduction
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

© Thomas Mailund 2023 1


T. Mailund, Functional Programming in R 4, https://doi.org/10.1007/978-1-4842-9487-1_1
Chapter 1 Introduction

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.

2
CHAPTER 2

Functions in R
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

© Thomas Mailund 2023 3


T. Mailund, Functional Programming in R 4, https://doi.org/10.1007/978-1-4842-9487-1_2
Chapter 2 Functions in R

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.

4
Chapter 2 Functions in R

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

5
Chapter 2 Functions in R

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

6
Chapter 2 Functions in R

Even parentheses and subscripting are functions. Parentheses


evaluate to the value you put inside them (but stripped of invisibility), and
subscripting, [...] or [[...]], evaluates to some appropriate value on the
data structure you are accessing (and you can define how this will work for
your own data structures if you want to).
If you want to return a value from a function before its last expression,
you can use the return function. It might look like a keyword, but it is a
function, and you need to include the parentheses when you use it. Many
languages will let you return a value by writing

return expression

Not R. In R, you need to write

return(expression)

If you are trying to return a value, this will not cause you much trouble.
R will tell you that you have a syntax error if you use the former and
not the latter syntax. Where it can be a problem is if you want to return
from a function without providing a value (in which case the function
automatically returns NULL).
If you write something like this:

f <- function(x) {
  if (x < 0) return;
  # Something else happens here...
}

you will not return if x is negative. The if-expression evaluates to the


function return, which is not what you want. Instead, you must write

f <- function(x) {
  if (x < 0) return();
  # Something else happens here...
}

7
Chapter 2 Functions in R

If x is negative, we call return(), which will return NULL. (To return a


value, val, use return(val)).
Return is usually used to exit a function early and isn’t used that
much in most R code. It is easier to return a value by just making it the last
expression in a function than it is to explicitly use return. But you can use
it to return early like this:

rescale <- function(x, only_translate) {


    m <- mean(x)
    translated <- x - m
    if (only_translate) return(translated)
    s <- sd(x)
    translated / s
}
rescale(1:4, TRUE)

## [1] -1.5 -0.5  0.5  1.5

rescale(1:4, FALSE)

## [1] -1.1618950 -0.3872983  0.3872983  1.1618950

This function has two arguments, x and only_translate. Your


functions can have any number of parameters. When a function takes
many arguments, however, it becomes harder to remember in which order
you have to put them. To get around that problem, R allows you to provide
the arguments to a function using their names. So the two function calls
earlier can also be written as

rescale(x = 1:4, only_translate = TRUE)


rescale(x = 1:4, only_translate = FALSE)

8
Chapter 2 Functions in R

Named Parameters and Default Parameters


If you use named arguments, the order doesn’t matter, so this is also
equivalent to these function calls:

rescale(only_translate = TRUE, x = 1:4)


rescale(only_translate = FALSE, x = 1:4)

You can mix positional and named arguments. The positional


arguments have to come in the same order as used in the function
definition, and the named arguments can come in any order. All the
following four function calls are equivalent:

rescale(1:4, only_translate = TRUE)


rescale(only_translate = TRUE, 1:4)
rescale(x = 1:4, TRUE)
rescale(TRUE, x = 1:4)

When you provide a named argument to a function, you don’t need to


use the full parameter name. Any unique prefix will do. So we could also
have used the following two function calls:

rescale(1:4, o = TRUE)
rescale(o = TRUE, 1:4)

This is convenient for interactive work with R because it saves some


typing, but I do not recommend it when you are writing programs. It can
easily get confusing, and if the author of the function adds a new argument
to the function with the same prefix as the one you use, it will break your
code. If the function author provides a default value for that parameter,
your code will not break if you use the full argument name. Not breaking,
in a situation like this, is a whole lot worse than breaking, because the code
will not do the right thing and you will not be immediately aware of that.

9
Chapter 2 Functions in R

Now, default parameters are provided when the function is defined.


We could have given rescale a default parameter for only_translate
like this:

rescale <- function(x, only_translate = FALSE) {


    m <- mean(x)
    translated <- x - m
    if (only_translate) return(translated)
    s <- sd(x)
    translated / s
}

Then, if we call the function, we only need to provide x if we are happy


with the default value for only_translate.

rescale(1:4)

## [1] -1.1618950 -0.3872983  0.3872983  1.1618950

R makes heavy use of default parameters. Many commonly used


functions, such as plotting functions and model fitting functions, have lots
of arguments. These arguments let you control in great detail what the
functions do, making them very flexible, and because they have default
values, you usually only have to worry about a few of them.

T he “Gobble Up Everything Else”


Parameter: “...”
There is a special parameter all functions can take called .... This
parameter is typically used to pass parameters on to functions called
within a function. To give an example, we can use it to deal with missing
values, NA, in the rescale function.

10
Chapter 2 Functions in R

We can write (where I’m building from the shorter version)

rescale <- function(x, ...) {


    m <- mean(x, ...)
    s <- sd(x, ...)
    (x - m) / s
}

If we give this function a vector x that contains missing values, it will


return NA:

x <- c(NA, 1:3)


rescale(x)

## [1] NA NA NA NA

It would also have done that before because that is how the functions
mean and sd work. But both of these functions take an additional
parameter, na.rm, that will make them remove all NA values before they do
their computations. Our rescale function can do the same now:

rescale(x, na.rm = TRUE)

## [1]  NA -1  0  1

The first value in the output is still NA. Rescaling an NA value can’t be
anything else. But the rest are rescaled values where that NA was ignored
when computing the mean and standard deviation.
The “...” parameter allows a function to take any named parameter
at all. If you write a function without it, it will only take the predetermined
parameters, but if you add this parameter, it will accept any named
parameter at all:

f <- function(x) x
g <- function(x, ...) x
f(1:4, foo = "bar")

11
Chapter 2 Functions in R

## Error in f(1:4, foo = "bar"): unused argument (foo = "bar")

g(1:4, foo = "bar")

## [1] 1 2 3 4

If you then call another function with “...” as a parameter, then all the
parameters the first function doesn’t know about will be passed on to the
second function:

f <- function(...) list(...)


g <- function(x, y, ...) f(...)
g(x = 1, y = 2, z = 3, w = 4)

## $z
## [1] 3
##
## $w
## [1] 4

In the preceding example, function f creates a list of named elements


from “...”, and as you can see, it gets the parameters that g doesn’t
explicitly take.
Using “...” is not particularly safe. It is often very hard to figure out
what it actually does in a particular piece of code. What is passed on to
other functions depends on what the first function explicitly takes as
arguments, and when you call a second function using it, you pass along
all the parameters in it. If the function you call doesn’t know how to deal
with them, you get an error:

f <- function(w) w
g <- function(x, y, ...) f(...)
g(x = 1, y = 2, z = 3, w = 4)

## Error in f(...): unused argument (z = 3)

12
Chapter 2 Functions in R

In the rescale function, it would have been much better to add the rm.
na parameter explicitly.
That being said, “...” is frequently used in R. Particularly because
many functions take very many parameters with default values,
and adding these parameters to all functions calling them would be
tedious and error-prone. It is also the best way to add parameters when
specializing generic functions, which is a topic for another book, Advanced
Object-Oriented Programming in R, by yours truly.

Lazy Evaluation
Expressions used in a function call are not evaluated before they are
passed to the function. Most common languages have so-called pass-by-­
value semantics, which means that all expressions given to parameters of
a function are evaluated before the function is called. In R, the semantic is
“call-by-promise,” also known as “lazy evaluation.”
When you call a function and give it expressions as its arguments,
these are not evaluated at that point. What the function gets is not the
result of evaluating them but the actual expressions, called “promises”
(they are promises of an evaluation to a value you can get when you need it),
thus the term “call-by-promise.” These expressions are only evaluated
when they are actually needed, thus the term “lazy evaluation.”
This has several consequences for how functions work. First of all, an
expression that isn’t used in a function isn’t evaluated:

f <- function(a, b) a
f(2, stop("error if evaluated"))

## [1] 2

f(stop("error if evaluated"), 2)

## Error in f(stop("error if evaluated"), 2): error if


evaluated

13
Chapter 2 Functions in R

If you have a parameter that can only be meaningfully evaluated in


certain contexts, it is safe enough to have it as a parameter as long as you
only refer to it when those necessary conditions are met.
It is also very useful for default values of parameters. These are
evaluated inside the scope of the function, so you can write default values
that depend on other parameters:

f <- function(a, b = a) a + b
f(a = 2)

## [1] 4

This does not mean that all the expressions are evaluated inside the
scope of the function, though. We discuss scopes in Chapter 4, but for now,
you can think of two scopes: the global scope where global variables live
and the function scope that has parameters and local variables as well.
If you call a function like this:

f(a = 2, b = a)

you will get an error if you expect b to be the same as a inside the function.
If you are lucky and there isn’t any global variable called a, you will get a
runtime error. If you are unlucky and there is a global variable called a, that
is what b will be assigned, and if you expect it to be set to 2 here, your code
will just give you an incorrect answer.
However, it is safe for a default parameter to be an expression that
uses some of the other function arguments. The default parameters are
evaluated after the function is called, where they have access to the other
arguments. An expression you use when calling a function, however,
doesn’t see the local variables inside the function, but the variables you
have in the calling scope.

14
Chapter 2 Functions in R

Figure 2-2. Where arguments and default arguments are evaluated

Consider Figure 2-2. We have a function, f, that takes two arguments,


a and b, where b has a default of 2*a. If we call it as f(2*a, b = 2*a), then
both arguments will be expressions that R knows have to be evaluated in
the global scope where a is the list 1 2 3 4 5 and where we don’t have a
b. Neither parameter will be evaluated until we look at the arguments, but
when we do, both will be evaluated and to the same value since both are
2*a and a refers to the global a. If, however, we call f as f(2*a) so b gets the
default value, we are in a different situation. Inside the function call, a still
refers to the expression 2*a to be evaluated in the global scope, but b, also
still referring to the expression 2*a, will be evaluated in the local scope. So,
if we evaluate b, we will first evaluate the parameter a to get 2*a (evaluated
using the global a) 2 4 6 8 10, and then we evaluate 2*a with this local a
to get 4 8 12 16 20.
So, while arguments aren’t evaluated yet when you call a function, they
will be when you access them. If they are default arguments, you evaluate
them inside the function, and if they were provided in the function call,
you evaluated them outside the call, where the function was called.

15
Chapter 2 Functions in R

This also means that you cannot change what an expression evaluates
to just by changing a local variable:

a <- 4
f <- function(x) {
    a <- 2
    x
}
f(1 + a)

## [1] 5

In this example, the expression 1 + a is evaluated inside f, but the a in


the expression is the a outside of f and not the a local variable inside f.
This is of course what you want. If expressions really were evaluated
inside the scope of the function, then you would have no idea what they
evaluated to if you called a function with an expression. It would depend
on any local variables the function might use.
Because expressions are evaluated in the calling scope and not the
scope of the function, you mostly won’t notice the difference between call-­
by-­value and call-by-promise. There are certain cases where the difference
can bite you, though, if you are not careful.
As an example, we can consider this function:

f <- function(a) function(b) a + b

This might look a bit odd if you are not used to it, but it is a function
that returns another function. We will see many examples of this kind of
functions in later chapters.
When we call f with a parameter a, we get a function back that will add
a to its argument:

f(2)(2)

## [1] 4

16
Chapter 2 Functions in R

We can create a list of functions from this f:

ff <- vector("list", 4)
for (i in 1:4) {
  ff[[i]] <- f(i)
}
ff

## [[1]]
## function(b) a + b
## <bytecode: 0x7fe446ad68a8>
## <environment: 0x7fe446a07ca0>
##
## [[2]]
## function(b) a + b
## <bytecode: 0x7fe446ad68a8>
## <environment: 0x7fe446ad71e8>
##
## [[3]]
## function(b) a + b
## <bytecode: 0x7fe446ad68a8>
## <environment: 0x7fe446ad7098>
##
## [[4]]
## function(b) a + b
## <bytecode: 0x7fe446ad68a8>
## <environment: 0x7fe446ad6f48>

Here, ff contains four functions, and the idea is that the first of these
adds 1 to its argument, the second adds 2, and so on.

17
Chapter 2 Functions in R

If we call the functions in ff, however, weird stuff happens:

ff[[1]](1)

## [1] 5

When we get the element ff[[1]], we get the first function we created
in the loop. If we substitute into f the value we gave in the call, this is

function(b) i + b

The parameter a from f has been set to the parameter we gave it, i, but
i has not been evaluated at this point!
When we call the function, the expression is evaluated, in the global
scope, but there i now has the value 4 because that is the last value it was
assigned in the loop. The value of i was 1 when we called it to create the
function, but it is 5 when the expression is actually evaluated.
This also means that we can change the value of i before we evaluate
one of the functions, and this changes it from the value we intended when
we created the function:

i <- 1
ff[[2]](1)

## [1] 2

This laziness is only in effect the first time we call the function. If we
change i again and call the function, we get the same value as the first time
the function was evaluated:

i <- 2
ff[[2]](1)

## [1] 2

18
Chapter 2 Functions in R

We can see this in effect by looping over the functions and


evaluating them:

results <- vector("numeric", 4)


for (i in 1:4) {
  results[i] <- ff[[i]](1)
}
results

## [1] 5 2 4 5

We have already evaluated the first two functions, so they are stuck at
the values they got at the time of the first evaluation. The other two get the
intended functionality but only because we are setting the variable i in
the loop where we evaluate the functions. If we had used a different loop
variable, we wouldn’t have been so lucky.
This problem is caused by having a function with an unevaluated
expression that depends on variables in the outer scope. Functions
that return functions are not uncommon, though, if you want to exploit
the benefits of having a functional language. It is also a consequence
of allowing variables to change values, something most functional
programming languages do not allow for such reasons. You cannot entirely
avoid it, though, by avoiding for-loops. If you call functions that loop for
you, you do not necessarily have control over how they do that, and you
can end up in the same situation.
The way to avoid the problem is to force an evaluation of the
parameter. If you evaluate it once, it will remember the value, and the
problem is gone.
You can do that by just writing the parameter as a single statement.
That will evaluate it. It is better to use the function force though, to
make it explicit that this is what you are doing. It really just gives you the
expression back, so it works exactly as if you just wrote the parameter, but
the code makes clear why you are doing it.

19
Chapter 2 Functions in R

If you do this, the problem is gone:

f <- function(a) {
  force(a)
  function(b) a + b
}

ff <- vector("list", 4)
for (i in 1:4) {
  ff[[i]] <- f(i)
}

ff[[1]](1)

## [1] 2

i <- 1
ff[[2]](1)

## [1] 3

Functions Don’t Have Names


The last thing I want to stress when we talk about defining functions is that
functions do not have names. Variables have names, and variables can
refer to functions, but these are two separate things.
In many languages, such as Java, Python, or C++, you define a function,
and at the same time, you give it an argument. When possible at all, you
need a special syntax to define a function without a name.
Not so in R. In R, functions do not have names, and when you define them,
you are not giving them a name. We have given names to all the functions
we have used earlier by assigning them to variables right where we defined
them. We didn’t have to. It is the “function(...) ...” syntax that defines a
function. We are defining a function whether we assign it to a variable or not.

20
Another random document with
no related content on Scribd:
degrees F.—and are immediately succeeded by marked increase in
the severity of the symptoms, both mental and physical, especially if
the attacks follow each other in rapid succession or last for a number
of days. They may be due to hemorrhage, embolism, or effusion,
and be marked by any or all of the usual symptoms and sequences
of those conditions, permanent or transient. General and aural
vertigo are not uncommon.

The muscular tremor before the last stages varies in different


muscles—excessive perhaps in the tongue, moderate in the fingers,
and so on. It may also seem slight as compared with the other
symptoms, or, on the other hand, be enormously exaggerated in
certain groups of muscles out of all proportion to all other indications.
At the end extreme and constant tremulousness accompanies every
voluntary movement.

Spastic paralysis, muscular tension, contractures, rigidity of the most


persistent character seem at times to be under the influence of the
will, although of cortical origin and in a certain sense automatic, like
convulsions.

The knee-jerk is changed in somewhat more than half the cases, a


little oftener exaggerated than abolished; but sometimes the reflexes
are enormously increased all over the body, so that a strong puff of
air in the face even will set the arms and legs going like a jumping-
jack. I have twice seen the patellar reflex abolished in one leg, and
so marked in the other as to seem to me exaggerated.24 I have also
known it to disappear absolutely in both legs two weeks after it had
been found to be excessively exaggerated. It also varies under
conditions of rest, fatigue, excitement, etc. Intense pain in the joints
occurs, and I have found it where the knee-jerk was exaggerated, in
one case giving rise in a physician to the delusion that his arms and
elbows had been resected. This may disappear in time. Charcot's
joint disease has been observed.
24 There was no evidence, and there had been no history, of a hemiplegic attack in
either case.
In the final stages the bones are fragile and easily break;
hemorrhages under the periosteum or perichondrium arise from
trifling force or injury, giving rise to hæmatomata, the most common
of which are on parts exposed to pressure, etc., as the ear. The
patient is confined to his bed, fed like a small child, demented, hardly
able to articulate the extravagant delusions which form such a
grotesque contrast to his actual state, until the mind is as incapable
of forming or receiving ideas as of expressing thoughts; and the
body is simply a filthy, helpless mass of humanity, dying of
exhaustion or decay, unless lung gangrene, bed-sores superficial
and deep, necrobiosis, exhausting diarrhœa, pneumonia, pulmonary
consumption, perhaps asphyxia from an epileptic fit or choking, have
followed incontinence of urine and feces to the fatal end, or heart
failure or apoplexy have closed the scene.

PATHOLOGY AND MORBID ANATOMY.25—General paralysis of the insane


is, according to Mendel, following Rokitansky's idea, a connective-
tissue disease, affecting the nerve-cells and tissues secondarily,
while Tuczek and Wernicke think that the primary disease is of the
nerve-elements (primäre Atrophie der Nervenelemente)—a diffuse
interstitial cortical encephalitis on the one hand, or a diffuse
parenchymatous cortical encephalitis on the other. There is also, in
well-marked cases, atrophy of the white substance, due, according
to general opinion of pathologists, to primary interstitial encephalitis
ending in sclerosis.
25 For a detailed statement of the post-mortem appearances in general paralysis
compare Spitzka's Insanity, pp. 218-243; Beiträge zur pathologischen Anatomie und
zur Pathologie der Dementia Paralytica, von Dr. Franz Tuczek; Die Progressive
Paralyse der Irren, von Dr. E. Mendel; Lehrbuch der Gehirnkrankheiten, von Dr. C.
Wernicke, iii. pp. 536-541. Westphal's classical work is not referred to, as his latest
views and others of interest are given in a report of a discussion by the German
Association of Alienists in the Allgemeine Zeitschrift für Psychiatrie, iv. 1883, pp. 634-
638 and 648-654. In the third number of the Neurol. Centralblatt, Mendel reports an
autopsy of a patient diagnosticated to have melancholia, who died a violent death,
where he thought that he found evidence of the early stage of general paralysis in
moderate opacity of the pia mater, with nodules as large as a pin's head in both
parietal regions, and in slight indications of diffuse interstitial inflammation of the
cortex, the blood-vessels in the frontal convolutions being extensively filled with white
blood-corpuscles.

In the majority of cases there is pachymeningitis, often extensive and


excessive, with hemorrhages, but which may be no more than is
quite commonly found in persons dying of phthisis or chronic
nephritis. There is also, usually, leptomeningitis, with adhesions to
the cortex, especially of the anterior and antero-lateral portions, so
firm that the arachnoid cannot be removed without tearing off
portions of the brain; but it is sometimes scarcely observed, and may
be no more than is found in persons dying simply of old age. The pia
may be in places thickened, opaque, and without adhesions.
Ependymitis is usual.

In the terminal stage of general paralysis there is well-marked


atrophy (with compensatory serous effusion), which is, as a rule,
most marked in the cortex of the brain, but which is of varying
degrees in its different portions. Rarely there is scarcely any atrophy
of the cortex. The central portion of the brain may be of leathery
consistence, but usually shows marked sclerosis, which also may
affect its different portions and the different ganglia very differently.
The changes resulting from inflammatory, degenerative, and atrophic
processes are general and profound.

An opinion is beginning to obtain that general paralysis is primarily a


disease of the small cerebral blood-vessels, functional or vaso-
motor; and Meynert holds that the transition line between that stage,
which he considers curable, and organic disease may be recognized
clinically.

In general paralysis, as in other mental diseases, the nervous


discharge is accompanied by a greater disturbance in the structure
of the gray substance of the brain, a more extensive decompounding
of it, and consequently by a more complete exhaustion of nervous
force than in healthy mental processes. Longer periods of rest and
improved nutrition are therefore necessary to restore healthy
function. In general paralysis, as in all other mental diseases
dependent upon destructive disease of the brain, there is not only
decompounding, but decomposing and disintegrating, of the
structure of the brain.

Posterior spinal sclerosis is frequently found. If alone or


predominating over sclerosis of the lateral columns of the cord, the
knee-jerk is abolished if the morbid process has gone far enough. If
descending degeneration of the lateral columns is chiefly found, and
is sufficiently advanced, the knee-jerk is increased. At least one of
these forms of sclerosis exists in the vast majority of cases.

There is also a distinctly syphilitic disease of the smaller cerebral


arteries, together with a diffuse parenchymatous and interstitial
encephalitis of syphilitic origin. At present we have no means of
differentiating it at the autopsy from general paralysis following a
subacute or chronic course, except inferentially from the presence of
other evidences of syphilis. It is not always possible, therefore, to
distinguish between syphilis and a syphilitic diathesis as the chief
factor in diffuse encephalitis.

DIAGNOSIS.—Although a well-marked case of general paralysis is


unmistakable, the diagnosis in the early stages or in obscure cases
may be extremely difficult. The varying degrees in which the various
portions of the cortex, medullary portion, and different ganglia of the
brain may be involved in the morbid process naturally give rise to a
great variety in the symptoms, mental and physical, sensory and
motor, emotional and intellectual, and in the relative preponderance
of one or another in individual cases. The usual symptoms of any
form of mental disease may for a time obscure the dementia which
sooner or later must appear in general paralysis, and which, as has
already been said, is the only mental symptom universally present in
all cases. This mental impairment must also be associated with
progressive muscular loss of power, although the relation of the two
symptoms to each other, the degree to which a given amount of the
one leads to a fair inference of a certain amount of the other, is liable
to the greatest variation, the range of which can only be learned by
observation and experience. There is a certain quality to the
dementia, as already described, which is often sufficient of itself to
establish the diagnosis with a practised physician.

The early mental symptoms may simulate those of cerebral


neurasthenia, in which the patient thinks that there is decided mental
impairment, although there is no progressive dementia. The tremor
in neurasthenia is greater and more universal than in the stage of
general paralysis with which it might be confounded, and the
subjective symptoms are much more prominent.

Muscular malaise and pains throughout the body give rise to the
diagnosis of malaria or rheumatism, in which there may be loss of
power, but no ataxia or dementia.

The sclerosis may be predominating or pronounced in the basal


ganglia and bulbar nuclei, giving occasion for a hasty diagnosis of
labio-glosso-pharyngeal paralysis, until it is found that the clinical
history of that disease is not followed. In the same way, any motor or
sensory ganglia or nerve-roots may be so early implicated in the
degenerative process as to mislead the physician into giving
attention to only the local symptoms.

Once I have known the early convulsions of general paralysis in a


very self-conscious woman mistaken for hysteria, the mental
impairment and physical weakness having been overlooked on
account of the prominence of the convulsive attacks and the
hysterical symptoms, which may be a complication of any form of
insanity in young and middle-aged people, particularly women.

It is not uncommon for the attacks to so thoroughly resemble


epilepsy as to be mistaken for it, the dementia not being observed or
being supposed to be the ordinary mental deterioration generally
following epilepsy. In such cases the progressive dementia, ataxia,
and muscular weakness may advance so slowly as to entirely
escape observation for a long time, and give rise to the confident
diagnosis of epilepsy for five or six years. Epilepsy, however, arising
in a vigorous, middle-aged person without evident cause, should
always suggest the suspicion of syphilis, cerebral tumor, or general
paralysis, when careful scrutiny of all the symptoms will show where
it belongs.

Embolisms, hemorrhages, cerebral effusions, more or less diffuse


encephalitis from an injury to the head, sometimes give rise to the
suspicion of general paralysis, until it is found that its characteristic
progressive symptoms do not appear, but chiefly when the history of
the case has not been definitely ascertained, or when the usual
symptoms of those conditions are not well marked.

Chronic endarteritis, arterio-sclerosis, atheroma of the cerebral


arteries may be so diffused as to simulate general paralysis,
especially in drunkards and syphilitics, but the symptoms do not
advance in the manner characteristic of that disease.

Multiple cerebro-spinal sclerosis of the descending form may be


confounded with general paralysis while the symptoms are obscure
and consist in change of character, when, indeed, organic disease
can only be suspected to be present.

Lead has been known to attack the central nervous system in such a
way as to produce an intellectual apathy and muscular weakness
somewhat resembling the early stage of the demented form of
general paralysis, but without its ataxic symptoms and its regular
progress. The presence of lead in the urine, and the marked
improvement from the use of iodide of potassium, tonics, and
electricity, are sufficient to establish the diagnosis.

Chronic and persistent alcoholism is always attended with some


mental impairment, which may so resemble the dementia of general
paralysis, with marked moral perversion, mental exaltation, grand
delusions, muscular tremor, ataxic symptoms, and impaired
muscular power, as to make the diagnosis doubtful for several
months, until removal of the cause (alcohol) in the course of time
causes the symptoms to so abate as to make the real character of
the disease evident.
I have once seen chronic interstitial nephritis without its usual
prominent symptoms and with mild uræmic convulsions mistaken for
general paralysis.

A tumor of the brain, if not attended with the common symptom of


vomiting, may be the cause of convulsions and headache
resembling those often seen in general paralysis. Optic neuritis or
atrophy is usual in cerebral tumor, but rare in a stage of general
paralysis so early that the diagnosis might be doubtful.

Hemorrhagic pachymeningitis also now and then simulates an


obscure case of general paralysis in the early stage, but a few weeks
at most settle any doubts in the matter.

Although diffuse cerebral syphilis is more apt to be associated with


distinctly localized symptoms than the demented form of general
paralysis, and although it is characterized by a mental apathy and
physical torpor which follow a more regular course with more definite
symptoms, resulting in a slow decay, yet there may be doubtful
cases in which the differential diagnosis is impossible, and in which
antisyphilitic treatment does not throw any light on the subject.
Syphilitic new growths, endarteritis, and meningitis may so far
improve from the use of mercury or the iodide of potassium as to end
in an apparent cure, but in those cases the symptoms are not so
marked as to make an exact diagnosis always possible. A distinct
syphilitic cachexia is presumptive evidence of syphilitic encephalitis
when there is doubt whether the syphilis is the cause or the
diathesis.

Profound melancholia is not so often as varying gloom or moderate


despondency a symptom of general paralysis. When it is such, there
are developed in time the other marks of that disease, and it will only
be necessary to hold the diagnosis in reserve for their appearance.
The melancholia masks the dementia unless it is very carefully
sought for, and the tremor may be as marked in melancholia as in
the early stage of general paralysis, but more universal.
Acute mania is not uncommonly mistaken for general paralysis,
when, as often happens, the delusions are as expansive and the
tremor as great in the mania as in general paralysis; and it may be
several months before the differential diagnosis can be made with
certainty. In the presence of a high degree of maniacal excitement,
with great emotional agitation and muscular tremor, it is difficult to
establish the fact of the existence or not of dementia in doubtful
cases until it is well developed. Acute mania has been known to
constitute the prodromal period of general paralysis for a number of
years.

Primary mental deterioration cannot be always differentiated from


general paralysis of the demented type in its early stage. After the
age of sixty the probabilities are in favor of primary mental
deterioration in doubtful cases, but general paralysis occurs—
seldom, to be sure—up to the age of sixty-five.

Early senile dementia may simulate general paralysis of the


subacute form, but has not its clinical history. General paralysis of
the quiet, insidious type and primary mental deterioration have been
called premature senility. The three diseased conditions have certain
points of similarity, and the pathological processes involved in them
do not differ sufficiently to authorize the assumption that they are not
closely related, if not simply variations, due to age and other causes,
in one morbid process.

Finally, the mental impairment caused by the prolonged use of


bromide of potassium and hydrate of chloral has been mistaken for
general paralysis, until a critical examination unmistakably showed
the presence of the well-known symptoms of those drugs.

In examining the patient it is especially important to avoid leading


questions, as in general paralysis and in those conditions which
simulate its early stage the mind is in a condition to readily fall into
the train of thought suggested to it. The fact should be kept in mind,
too, that the symptoms in early general paralysis are so variable as
to be sometimes quite evident, and at other times not to be got at
with certainty at all or only after long and patient examination; that
they sometimes quite disappear under the influence of complete
mental and bodily rest; and that in all stages, until near the end, such
complete remissions may occur as to make the diagnosis,
independent of the history of the case, difficult if not impossible.

A gentleman once committed an offence characteristic of general


paralysis in marrying a pretty servant-girl while temporarily away
from his home. His wife, daughters, and friends saw that the act was
so contrary to his natural character that he was placed in an insane
asylum and kept there several weeks under observation for an
opinion as to his responsibility. He appeared so well in the absolute
quiet and rest that he was declared sane, tried, and sentenced to the
State prison, where he showed his marked mental impairment as
soon as he was set to work. He could not concentrate his mind
sufficiently for the simplest labor, and a couple of years later he was
sent to the insane asylum to die, a complete mental and physical
wreck, in the late stage of general paralysis.

PROGNOSIS.—The very few reported cures in so common a disease


as general paralysis, and the circumstances under which they have
been reported, lead to the suspicion that there was an error in
diagnosis or that the mistake was made of supposing a remission to
be a cure, as has often happened. The course of the disease is more
rapid in men than women, and in young persons than in the older.
From the galloping cases of a couple of months to those slowly
advancing, with long remissions, over twenty years, the average,
including the prodromal period, is probably not far from five (perhaps
six) years. Collected from asylum statistics, it is given as from two to
three years. When I am sure of the diagnosis, I generally say that the
patient may die within twenty-four hours (of paralysis of the heart,
from suffocation by an accident in an epileptic attack, from choking,
from cerebral hemorrhage or effusion, or suddenly with cerebral
symptoms of which the autopsy gives no satisfactory explanation),
within a short time of intercurrent disease, especially diarrhœa or
pneumonia, or that he may live several years, as he probably will,
and possibly have a remission, during which he may lead for a while
somewhat the same kind of life as other people.
Persons presenting symptoms which can in no way be positively
distinguished from those at the beginning of the prodromal period of
general paralysis recover, but not many come under the physician's
care so early. We are not yet in a position to say whether they were
suffering from a mild, transient illness or from what would otherwise
have become serious organic disease.

TREATMENT.—Life may be prolonged in general paralysis, and usually


is prolonged, by the use of such measures as contribute to the
patient's comfort, and which in a general way have already been
considered under the head of treatment of mental disease on a
previous page.

In my experience, stimulating tonics, wine, and even coffee, increase


the morbid cerebral energy of the early stage of the disease, but are
sometimes of use later. Cod-liver oil and the hypophosphites do
better, and many of the disagreeable symptoms of the period of loss
of control over the involuntary muscles are relieved by strychnia.
Ergot and the judicious use of the bromides abate the cerebral
congestion. Gastro-intestinal disorders, when not controlled by
attention to diet, require the usual treatment.

Iodide of potassium in the large or small dose, and mercury, I have


never found to benefit those cases of general paralysis with a
previous history of syphilis. On the contrary, they have proved
debilitating and harmful.

When furious excitement is not relieved by prolonged warm baths,


with cool applications to the head if possible, and quiet, chloral is of
use, and sometimes opium and its preparations.

Frequently-repeated violent convulsions, the epileptic state, are


usually at once mitigated by chloral given by the rectum; the
inhalation of nitrite of amyl is reported also to have been of use.

There are few cases in which I find that morphine does not quiet
restlessness, calm delusions, abate distressing hallucinations, and
make the patient generally more comfortable; and I give it freely,
seldom more than twice a day, often almost daily, for two or three
years. In this way it can be used in quite moderate doses. Coca also
relieves symptoms.

Rest and quiet are most important in all stages of the disease. This
can be best accomplished in a quiet private house in the country,
which can be made a virtual hospital, and next in a private asylum.
But such care is beyond the reach of the vast majority of the insane,
to whom the public asylum becomes a necessity. Wherever they are,
an orderly life is best for them, with as little irritating interference with
their ways or control of them as is possible.

If the results of treatment are in the highest degree unsatisfactory,


and consist chiefly in meeting symptoms as they come up, without
hope of permanent recovery, it is not impossible that when we can
put the patient under treatment at the very beginning of his disease,
as we can now do in pulmonary consumption, the prognosis in the
former disease may change as much for the better as it has changed
in the latter.

A general paralytic is at any time liable to congestive or maniacal


attacks of short duration, and so is always, potentially, a dangerous
person. In the prodromal period the risk is small; in all stages there
will, in the majority of cases, be some warning; but in the developed
disease the only safe way is to have some responsible person near
at hand, both to prevent the patient from doing harm to others and to
save him from injuring himself, whether by intent or through not
knowing better than to wander off or fall into all sorts of accidents. In
many conditions several should be readily available, or else the
security of an asylum must be sought.

In the treatment of general paralysis by society the same rule should


obtain as in all forms of insanity—that distinct mental disease is
presumptive proof of irresponsibility, or at least of limited
responsibility; that a diseased mind means lessened intellectual
power throughout and diminished ability to choose the right and
avoid the wrong; that there are changes in circulation or nutrition, or
some unknown condition in the brain, especially in general paralysis,
by virtue of which the mental state and power of self-control vary
from time to time, and as a result of which a person seeming
responsible one day may have been quite irresponsible some
previous day.

INSANITY FROM GROSS LESIONS OF THE BRAIN (tumors, new growths of


all kinds, exostoses, spicules or portions of depressed bone,
embolisms, hemorrhages, wounds, injuries, cysticerci, etc.) is
attended with the usual indications of those conditions which may
determine diffuse disorders of the brain, giving rise to any of the
symptoms of the various psycho-neuroses and cerebro-psychoses.
The lowered mental and moral tone after cerebral hemorrhages is a
matter of common observation, and after one an individual is rarely
observed to be fully himself again.

The PROGNOSIS is very unfavorable. Although there are rare cases of


improvement, the tendency is toward profound dementia.

CEREBRAL SYPHILITIC INSANITY comes either under the head of the


insanity last described or belongs to the slowly-advancing dementia
with final paralysis already referred to under the head of Diagnosis in
General Paralysis, and called by some authorities on mental disease
pseudo-paralytic dementia from syphilis.

Antisyphilitic treatment is of value in the first class of cases, and


although most of the recoveries end in relapses and incurability, the
prolonged use of iodide of potassium seems sometimes to effect a
permanent cure. It is claimed that similar treatment is followed by the
same result in the cases of dementia with paresis, but the weight of
authority, and certainly my own experience, are against that
statement.

CHRONIC ALCOHOLIC INSANITY depends upon the vascular and other


changes due to abuse of alcohol so long continued that the
pathological condition has become organic and incurable. It is
commonly associated with delusions of suspicion or persecution. It
may be a purely moral insanity, with gross beliefs rather than
distinctly insane delusions, and it rarely fails to be at least that when
the persistent excessive drinking is kept up until the age of beginning
dissolution of the brain. It then gives rise to all sorts of embarrassing
complications in regard to property, family relations, and wills.
Chronic alcoholic insanity may take the form of mild dementia, by
virtue of which the patient cannot control himself, but can be easily
kept within bounds of reasonable conduct by various degrees of
restraint, from the constant presence of a responsible person to the
seclusion of an asylum. In well-marked cases this dementia is
associated with muscular weakness, tremor, and exhilaration to such
an extent as to simulate general paralysis. It is then called by some
—especially French—writers pseudo-paralytic dementia from
alcohol.

The condition is susceptible of improvement by removal of the


cause, alcohol, and by a carefully-regulated life, hydropathic
treatment, etc., but complete recoveries cannot be expected.

SECONDARY DELUSIONAL INSANITY is slowly developed from various


mental diseases, incurable or uncured, where the progress to
marked dementia is slow, by the persistence of delusions in those
forms of insanity characterized by delusions. It is chronic and
incurable. In melancholia and mania the mental depression and the
exaltation and motor excitement disappear to a great extent, and
there are left a slowly-advancing dementia, confusion, and
expanding delusions, with apathy or with agitation, for which the
asylum is the only safe place unless physical weakness makes the
patient harmless. It is either a terminal state in which many forms of
insanity end, or a stage through which they pass to terminal
dementia. It depends upon incurable, and therefore organic,
changes in the brain, like all incurable insanity, although those
changes are not yet determined exactly. It might be a question
whether chronic delusional insanity properly belongs under the head
of Organic Mental Diseases, and a similar criticism may be made
regarding terminal dementia. But in this paper no definite
classification of insanity is attempted, because our knowledge of the
subject is still so indefinite, although the several mental diseases are
grouped in a certain order for convenience to the reader and the
writer; and this order of course approximately follows natural lines.

TERMINAL DEMENTIA is the end to which most of the insanity not


resulting in recovery finally comes. The features marking the disease
in its early stages for the most part disappear, leaving all the
functions of the mind impaired in all degrees up to total extinction—
the whole character on a lower plane. It is the disease which to so
great an extent crowds the wards of insane asylums and
almshouses with the (1) agitated or (2) apathetic chronic insane, the
worst of whom are mental and physical wrecks, squatting on floors,
uttering an unintelligible jargon, noisy, filthy, without intelligence for
the simplest natural wants. Their chief function, under the prevalent
methods of construction and management of lunatic hospitals in
most places, is to blight with a certain feeling of hopelessness many
of the curable insane who are obliged to go for rest and quiet to
institutions where the overwhelming majority of the inmates are
manifestly and painfully incurable.

French writers include a great part of chronic delusional insanity


(secondary confusional insanity, Wahnsinn, secundäre Verrücktheit)
and terminal dementia (Blödsinn) under one head, démence; and
with much reason, as it is not always possible to differentiate
between the two.

The proper TREATMENT of the incurable, demented insane should


provide not only that they be not at large, where they annoy the
strong and the well, but also that they shall not disturb the insane
who are acutely ill and in need of treatment suited to sick people,
and whose chances of recovery at best are none too favorable.
Experiments, now quite numerous, have shown that the lives and
occupations of many of them may be made not entirely unlike those
to which they were reared, and that nearly all may be suitably
provided for without the expensive hospitals and appliances
necessary for the proper treatment of acute mental disease.

A comparison of countries in which there is and is not a


comprehensive system of State supervision of the insane by a
competent board seems to me to reveal so unquestionably the fact
that such a system alone provides the proper protection for the
insane, and the needed variety and uniformly high standard of
excellence in the provisions for their treatment, that I hope to see the
medical profession using its vast influence upon public opinion to
secure it.

If we meet in the wards of our insane asylums hopeless mental and


physical wrecks, if we find there the extremity of human
wretchedness, the supreme control of all that is evil or vile in our
nature, the worst antitypes of all the virtues, so, on the other hand,
nowhere else do we see such struggles for the mastery of the better
impulses, such efforts against such odds to hold back the mind in an
unequal fight. Nowhere else, too, are developed finer sympathy,
more beautiful unselfishness, more generous charity, or more heroic
resignation where no hope in life remains but for death.

The State has taken charge of these most unfortunate people,


shutting up behind the same locked doors and barred windows
people of all social grades, often mingling together in one presence
the so-called criminal insane, insane criminals, idiots, imbeciles,
epileptics, paralytics, the chronic insane, and the demented, with
patients suffering from acute mental disease. Some of them are
unconscious of their condition, many are better off than ever before,
but others are painfully alive to their situation and surroundings, fully
aware of the gravity of their illness, keenly sensitive to the
distressing sights and associations, disturbed by the noises, and
discouraged by the many chances of becoming like the worst
incurables around them. The State cannot evade the responsibility of
seeing that their confinement is made the least rigorous, wretched,
and injurious possible.
HYSTERIA.
BY CHARLES K. MILLS, M.D.

DEFINITION.—Hysteria is a functional disease of the cerebro-spinal


axis, characterized either by special mental symptoms or by motor,
sensory, vaso-motor, or visceral disorders related in varying degree
to abnormal psychical conditions.

This, like all other definitions of hysteria, is imperfect. No absolutely


satisfactory definition can well be given. It is not abnormal ideation,
although this is so often prominent; it is not emotional exaltation,
although this may be a striking element; it is not perversion of
reflexes and of sensation, although these may be present. Some
would make it a disease of the womb, others an affection of the
ovaries; some regard it as of spinal, others as of cerebral origin;
some hold it to be a disease of the nerves, others claim that it is a
true psychosis; but none of these views can be sustained.

Sir James Paget1 says of hysterical patients that they are as those
who are color-blind. They say, “I cannot;” it looks like “I will not,” but it
is “I cannot will.” Although, however, much of the nature of hysteria is
made clear in this explanation, hysteria is not simply paralysis of the
will. A true aboulomania or paralysis of the will occurs in non-
hysterical patients, male and female, and of late years has been
studied by alienists.
1 “Clinical Lecture on the Nervous Mimicry of Organic Diseases,” Lancet for October,
November, and December, 1873.

In many definitions the presence of a spasmodic seizure or


paroxysm is made the central and essential feature; but, although
convulsions so frequently occur, typical hysterical cases pass
through the whole course of the disorder without suffering from
spasm of any kind.
In a general neurosis a definition, well considered, should serve the
purpose of controlling and guiding, to a large extent at least, the
discussion of the subject.

The definition given asserts that hysteria is a functional disease. In


the present state of knowledge this is the only ground that can be
taken. It is claimed that in a strict sense no disease can be regarded
as functional; but it is practically necessary to use such terms as
functional in reference to affections in which disordered action
without recognizable permanent alteration of structure is present.
Temporary anatomical changes must sometimes be present in
hysteria; organic disease may be a complication in special cases;
post-mortem appearances may occasionally be found as accidents
or coincidences; it is possible that structural alterations may result
from hysteria; but no pathologist has as yet shown the existence of a
special morbid anatomy underlying as a permanent basis the
hysterical condition.

The mental, motor, sensory, and other phenomena of hysteria


cannot be explained except by regarding the cerebro-spinal nervous
system as the starting-point or active agency in their production.

The term vaso-motor is used in a broad sense to include not only


peripheral vascular disturbances, but also cardiac, respiratory,
secretory, and excretory affections of varying type. Some of these
disorders are also visceral, but under visceral affections are also
included such hysterical phenomena as abdominal phantom tumors,
hysterical tympanites, and the like.

That all hysterical phenomena are related in varying degree to


abnormal psychical conditions may perhaps, at first sight, be
regarded as open to dispute and grave doubt. It is questionable
whether in every case of hysteria the relation of the symptoms to
psychical states could be easily demonstrated. I certainly do not look
upon every hysterical patient as a case of insanity in the technical
sense, but hold that a psychical element is or has been present,
even when the manifestations of the disorder are pre-eminently
physical. James Hendrie Lloyd,2 in a valuable paper, has ably
sustained this position, one which has been held by others, although
seldom, if ever, so clearly defined as by this writer.
2 “Hysteria: A Study in Psychology,” Journal of Nervous and Mental Disease, vol. x.,
No. 4, October, 1883.

The alleged uterine origin of hysteria has been entirely disregarded


in the definition. This has been done intentionally. It is high time for
the medical profession to throw off the thraldom of this ancient view.
The truth is, as asserted by Chambers,3 that hysteria “has no more
to do with the organs of reproduction than with any other of the
female body; and it is no truer to say that women are hysterical
because they have wombs, than that men are gouty because they
have beards.”
3 Brit. Med. Journ., December 21, 1861, 651.

SYNONYMS.—Hysterics, Vapors. Many Latin and other synonyms


have been used for hysteria: most of these have reference to the
supposed uterine origin of the disease, as, for instance, Uteri
adscensus, Asthma uteri, Vapores uterini, Passio hysterica,
Strangulatio uterina seu Vulvæ. Some French synonyms are Maladie
imaginaire, Entranglement, and Maux ou attaques de nerfs. Other
French synonyms besides these have been used; most of them are
translations from the Latin, having reference also to the uterine
hypothesis. In our language it is rare to have any other single word
used as a synonym for hysteria. Sir James Paget4 introduced the
term neuromimesis, or nervous mimicry, and suggested that it be
substituted for hysteria, and neuromimetic for hysterical.
Neuromimesis is, however, not a true synonym. Many cases of
hysteria are cases of neuromimesis, but they are not all of this
character. Among the desperate attempts which have been made to
originate a new name for hysteria one perhaps worthy of passing
notice is that of Metcalfe Johnson,5 who proposes to substitute the
term ganglionism, as giving a clue to the pathology of hysteria. His
main idea is that hysteria exhibits a train of symptoms which are
almost always referable to the sympathetic or ganglionic nervous
system. This is another of those half truths which have misled so
many. The term hysteria, from the Greek ὑστερα, the uterus,
although attacked and belabored, has come to stay; it is folly to
attempt to banish it.
4 Op. cit.

5 Med. Times and Gaz., 1872, ii. 612.

METHOD OF DISCUSSING THE SUBJECT.—It is hard to decide upon the


best method of discussing the subject of hysteria. One difficulty is
that connected with the question whether certain affections should
be considered as independent disorders or under some subdivisions
of the general topic of hysteria. Certain great phases of hysteria are
represented by hystero-epilepsy, catalepsy, ecstasy, etc.; but it will
best serve practical ends to treat of these in separate articles. They
have distinctive clinical features, and are capable of special definition
and discussion.

HISTORY AND LITERATURE.—To give a complete history of hysteria it


would be necessary to traverse the story of medicine from the time
of Hippocrates to the present. A complete bibliography would require
an immense volume. Volume vi. of the Index Catalogue of the
Library of the Surgeon-General's Office, United States Army, which
has appeared during the present year (1885), contains a
bibliography of nearly seventeen double-column pages, most of it in
the finest type. The references are to 318 books and 914 journals.
The number of books and articles cited as having appeared in
different languages is as follows: Latin, 99; Greek, 2; German, 180;
British, 177; American, 159; French, 449; Italian, 75; Spanish, 45;
Swedish, 12; miscellaneous, 34. Even this wonderful list probably
only represents a tithe of the works written on this subject. Those
desirous of studying it from a bibliographical point of view can do so
by consulting this great work.

Many as are the names and voluminous as is the literature, certain


names and certain works are pre-eminent—Sydenham, Laycock,
and Skey in England; Tissot, Briquet, Charcot, and Landouzy in
France; Stahl, Frank, Eulenburg, and Jolly in Germany; and in

Вам также может понравиться