Converting a collection of response times to minutes requires the same calculation for each duration. For other calculations, we must first decide whether the available inputs support a result, as when a mean depends on a response count that may be zero or missing. We need a way to define both the calculation and those decisions, then apply them to different inputs. This chapter develops functions for that purpose. We examine what a call receives, which names it uses, and what it returns, then add conditional branches and collect results through iteration. Finally, we pass the calculation itself to a function that repeats it.
Converting seconds to minutes always divides by 60, whether the duration is 30 seconds or 90. A function defines the calculation once. Its parameter, seconds, names the input that can vary. In the call to_minutes(30), the argument 30 gives the duration in seconds.
In R, function(seconds) { seconds / 60 } defines a function with one parameter, seconds. The braces enclose its body, the code to run for each call. The assignment gives the function the name to_minutes and displays nothing. In to_minutes(30), seconds takes the value 30 for that call. R returns the value of the last expression in this body to the caller, the code that made the call.
1
2
3
4
5
| to_minutes <- function(seconds) {
seconds / 60
}
to_minutes(30)
to_minutes(90)
|
At the Console, entering to_minutes(30) displays its return value, 0.5, even though the function contains no print(). Because both calls return numbers, to_minutes(30) + to_minutes(90) can use their results directly.
1
2
| total_minutes <- to_minutes(30) + to_minutes(90)
total_minutes
|
Some calculations need more than one input. To express how far a score is above or below a reference, we subtract the reference from the score. This function has two parameters, value and reference. The default reference = 3 means that a call with only the score subtracts 3.
1
2
3
4
5
| subtract_reference <- function(value, reference = 3) {
value - reference
}
subtract_reference(2)
subtract_reference(5)
|
R matches the arguments in subtract_reference(5, 3) by position. Naming both arguments allows them to appear in either order. Here the first four calls all subtract 3 from 5. The last call changes the reference to 4.
1
2
3
4
5
| subtract_reference(5, 3)
subtract_reference(5, reference = 3)
subtract_reference(reference = 3, value = 5)
subtract_reference(5)
subtract_reference(5, reference = 4)
|
1
2
3
4
5
| [1] 2
[1] 2
[1] 2
[1] 2
[1] 1
|
In Python, def to_minutes(seconds): defines the function and names its parameter. The colon introduces the body, and the four-space indentation marks the line that belongs to it. In to_minutes(30), seconds is 30. The statement return seconds / 60 sends the result to the caller, the code that made the call. The definition itself displays nothing. At the Console, a blank line ends the definition. In a script, two blank lines conventionally separate a top-level definition from the code that follows.
1
2
3
4
5
6
| def to_minutes(seconds):
return seconds / 60
to_minutes(30)
to_minutes(90)
|
The sum to_minutes(30) + to_minutes(90) uses the two numbers returned by those calls. show_minutes() displays the conversion with print() and has no return. The assignment to shown lets you check what the caller received.
1
2
3
4
5
6
7
8
9
10
| total_minutes = to_minutes(30) + to_minutes(90)
total_minutes
def show_minutes(seconds):
print(seconds / 60)
shown = show_minutes(90)
shown is None
|
1
2
| # Deliberate error: arithmetic on a function's None return
show_minutes(90) + 1
|
1
2
| 1.5
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
|
Why does the error mention NoneType when you can see 1.5? The 1.5 comes from print(). When show_minutes(90) reaches the end without a return statement, it returns None. That is the value assigned to shown in the first example and the value the addition receives in the second.
Some calculations need more than one input. A score of 2 is one point below a reference of 3, and subtract_reference() expresses that as a signed difference, value - reference. The score is required. If the call omits reference, the function subtracts 3.
1
2
3
4
5
6
| def subtract_reference(value, reference=3):
return value - reference
subtract_reference(2)
subtract_reference(5)
|
Python matches arguments by position or by keyword, as in reference=3. In the first four calls, the score is 5 and the reference is 3. The last call overrides the default with reference=4.
1
2
3
4
5
| subtract_reference(5, 3)
subtract_reference(5, reference=3)
subtract_reference(reference=3, value=5)
subtract_reference(5)
subtract_reference(5, reference=4)
|
4.2 Local names, scope, and argument evaluation
A function can name an intermediate result before returning it. If a subtraction function assigns its answer to difference, does that name become available to the caller too? To understand what a call depends on, we need to distinguish names created inside the function from names it reads outside. When an argument is itself a calculation, the timing of its evaluation also matters.
Inside relative_score(), print(difference) displays the difference during the call. The final expression, difference, returns that number, which the caller stores as result. Entering result then displays it a second time.
1
2
3
4
5
6
7
| relative_score <- function(value, reference = 3) {
difference <- value - reference
print(difference)
difference
}
result <- relative_score(5)
result
|
1
2
| # Deliberate error: a local name used outside its call
difference
|
1
| Error: object 'difference' not found
|
The caller can retrieve 2 as result. The lookup of difference failed because the function defined that name locally. Returning the number does not define difference at the Console.
The function subtract_outside() uses outside_reference without defining it as a parameter or a local name. An environment in R associates names with values. R first looks for the name locally, then in the environment where the function was defined. Here that is the global environment, where the Console assignments are made. If needed, the search continues and can reach attached packages. These rules determine the scope of a name.
1
2
3
4
5
6
7
| outside_reference <- 3
subtract_outside <- function(value) {
value - outside_reference
}
subtract_outside(5)
outside_reference <- 4
subtract_outside(5)
|
Both calls are written subtract_outside(5). The result changes from 2 to 1 because the second call subtracts the new global value, 4.
Giving subtract_given() a reference parameter lets the call specify 3 even as outside_reference changes. Which function will the new global value affect?
1
2
3
4
5
6
7
| subtract_given <- function(value, reference) {
value - reference
}
subtract_given(5, reference = 3)
outside_reference <- 5
subtract_given(5, reference = 3)
subtract_outside(5)
|
Even after outside_reference changes to 5, subtract_given(5, reference = 3) still subtracts 3 and returns 2. subtract_outside(5) now subtracts 5 and returns 0.
The reference examples establish where a function obtains a value. A separate question is when an argument expression is evaluated. stop() raises an error if it runs, so passing it as an unused argument lets us observe whether evaluation occurs. Here that call is the second argument to keep_value(), whose body uses only the first.
1
2
3
4
| keep_value <- function(value, unused) {
value
}
keep_value(5, stop("unused argument was evaluated"))
|
No error occurred. This function never needed the second argument, so R never evaluated it. Arguments to R functions such as this one are evaluated when needed, behavior called lazy evaluation.
The Python definition of relative_score() returns the value of its intermediate difference. The caller assigns that value to result. Does difference also work at the Console?
1
2
3
4
5
6
7
| def relative_score(value, reference=3):
difference = value - reference
return difference
result = relative_score(5)
result
|
1
2
| # Deliberate error: a local name used outside its call
difference
|
1
| NameError: name 'difference' is not defined
|
The caller can retrieve 2 as result. The name difference belongs to this function call, so looking it up at the Console raises NameError. Returning the number does not define difference in the caller’s namespace.
subtract_outside() reads outside_reference, a name defined at the top level of the session. In this function, that name is global. Python looks it up in the function’s global namespace because the function has no local binding for it. If a name is absent there too, Python checks its built-in names, such as print. These rules determine the scope of a name.
1
2
3
4
5
6
7
8
9
10
| outside_reference = 3
def subtract_outside(value):
return value - outside_reference
subtract_outside(5)
outside_reference = 4
subtract_outside(5)
|
The result changed from 2 to 1 when the global reference changed, despite the identical call.
In subtract_given(5, reference=3), the call specifies the reference. Which function’s result changes when outside_reference becomes 5?
1
2
3
4
5
6
7
8
| def subtract_given(value, reference):
return value - reference
subtract_given(5, reference=3)
outside_reference = 5
subtract_given(5, reference=3)
subtract_outside(5)
|
After outside_reference changes to 5, subtract_given(5, reference=3) still subtracts 3 and returns 2. subtract_outside(5) reads the new global value and returns 0.
The reference examples establish where a function obtains a value. A separate question is when an argument expression is evaluated. In subtract_given(5, reference=1 + 2), Python evaluates 1 + 2 before running the body, so the parameter receives 3.
1
| subtract_given(5, reference=1 + 2)
|
keep_value() ignores its second parameter. Both 3 and 1 / 0 appear in that position, but only the division can reveal whether Python evaluates it.
1
2
3
4
5
| def keep_value(value, unused):
return value
keep_value(5, 3)
|
1
2
| # Deliberate error: an unused argument that fails when evaluated
keep_value(5, 1 / 0)
|
1
| ZeroDivisionError: division by zero
|
The division by zero raises an error before Python enters the body of keep_value(). The return statement never runs.
In these examples, subtract_given() obtains both numbers from its arguments, while subtract_outside() also depends on a global value. The identical calls to subtract_outside(5) can therefore produce different results. Argument evaluation is a separate issue: the R function does not evaluate its unused argument, whereas Python evaluates the argument expressions before entering the function body.
4.3 Choosing a branch with one condition
For a total of 9 points from 3 responses, the mean is 3 points per response. What should a function return if the response count is zero or missing?
A zero count means there are no responses to average. A missing count means the denominator is unknown. In either case, the mean is unavailable. The functions below assume that an observed count is a single nonnegative whole number. They do not validate that assumption.
To choose a branch, or block of code to run, R must be able to interpret the if condition as a single TRUE or FALSE. For a missing count, missing_count > 0 tests whether the count is positive, and is.na(missing_count) tests whether it is missing. What happens if if uses the first test?
1
2
3
| missing_count <- NA
missing_count > 0
is.na(missing_count)
|
1
2
3
4
| # Deliberate error: an unknown condition in if
if (missing_count > 0) {
"positive"
}
|
1
| Error in if (missing_count > 0) { : missing value where TRUE/FALSE needed
|
The comparison gives NA, which cannot choose a branch. is.na() gives the definite TRUE needed to handle absence before testing positivity.
In mean_from(), the first branch gives NA when the count is missing. For an observed count, else if tests count > 0 and divides total by count when that test is true. For a count of zero, else gives NA. Dividing 9 by zero would give Inf, an infinite result. The if expression is last in the function body, so the function returns the value of the selected branch.
1
2
3
4
5
6
7
8
9
| mean_from <- function(total, count) {
if (is.na(count)) {
NA
} else if (count > 0) {
total / count
} else {
NA
}
}
|
All three test calls use 9 for the total. Only the count changes.
1
2
3
| mean_from(9, 3)
mean_from(9, 0)
mean_from(9, NA)
|
1
2
3
| [1] 3
[1] NA
[1] NA
|
The call with 3 responses returns 3 points per response. The other two calls both return NA. The input count distinguishes zero responses from an unknown number of responses. The comparison c(3, 0, NA) > 0 gives three answers, so it cannot serve as a single if condition.
Here None represents a missing count. Testing count is None first avoids comparing None with 0, which would raise TypeError.
1
2
| missing_count = None
missing_count is None
|
In Python, an if statement runs an indented block of code, or branch, when its condition is true. In mean_from(), if count is None selects the branch that returns None. For an observed count, elif count > 0 selects division when the count is positive. For zero responses, else returns None without dividing by zero, which would raise ZeroDivisionError. Each branch begins with a line ending in a colon, and only one branch runs per call.
1
2
3
4
5
6
7
| def mean_from(total, count):
if count is None:
return None
elif count > 0:
return total / count
else:
return None
|
The total is 9 in all three calls so that only the count changes. print() makes each returned None visible alongside the numerical mean.
1
2
3
| print(mean_from(9, 3))
print(mean_from(9, 0))
print(mean_from(9, None))
|
With 3 responses, the function returns 3.0 points per response. Both a zero count and a missing count give None. To tell which occurred, you need the input count.
mean_from() makes one decision per call: its single count determines whether the corresponding total can be divided.
4.4 Iteration and building a collection of results
Once a function defines what one call should return, we can repeat it for several inputs. To examine how the results are collected, return to the simple time conversion with recorded durations of 30, 90, and 120 seconds. A loop calls to_minutes() for each duration, and each repetition is an iteration. If every iteration assigns its result to minutes, which conversion can you retrieve from minutes after the loop?
In R, for (duration in durations) binds duration to each element in turn and runs the body between braces. The loop prints every conversion. The final minutes and duration expressions show which result and input you can still retrieve after the loop.
1
2
3
4
5
6
7
| durations <- c(30, 90, 120)
for (duration in durations) {
minutes <- to_minutes(duration)
print(minutes)
}
minutes
duration
|
1
2
3
4
5
| [1] 0.5
[1] 1.5
[1] 2
[1] 2
[1] 120
|
The first three lines show all three conversions. Reading minutes after the loop displays 2 again because each new assignment replaced the preceding result. Reading duration displays the last input, 120 seconds.
To retrieve every conversion after the loop, each result needs a position of its own. numeric(length(durations)) creates a vector of three zeros, one position per duration. seq_along(durations) gives the positions 1, 2, and 3. At each position, the loop converts one duration and replaces the zero with the result.
1
2
3
4
5
6
7
| all_minutes <- numeric(length(durations))
all_minutes
for (i in seq_along(durations)) {
all_minutes[i] <- to_minutes(durations[i])
print(all_minutes)
}
all_minutes
|
1
2
3
4
5
| [1] 0 0 0
[1] 0.5 0.0 0.0
[1] 0.5 1.5 0.0
[1] 0.5 1.5 2.0
[1] 0.5 1.5 2.0
|
The completed vector contains all three conversions in input order. R displays the final 2 minutes as 2.0 alongside the fractional values. Here to_minutes(durations) can convert the whole vector in one call because its body divides each element by 60. identical(all_minutes, durations / 60) compares the loop result with direct division, including their values, type, and attributes.
1
2
3
| durations / 60
to_minutes(durations)
identical(all_minutes, durations / 60)
|
1
2
3
| [1] 0.5 1.5 2.0
[1] 0.5 1.5 2.0
[1] TRUE
|
In Python, for duration in durations: binds duration to each item and runs the indented body. A blank line at the Console ends the block. Printing inside the loop shows every conversion. Evaluating minutes and duration afterward shows what those names still refer to.
1
2
3
4
5
6
7
| durations = [30, 90, 120]
for duration in durations:
minutes = to_minutes(duration)
print(minutes)
minutes
duration
|
1
2
3
4
5
| 0.5
1.5
2.0
2.0
120
|
After the loop, duration is 120 seconds and minutes is 2.0 minutes. Each new assignment to minutes replaced the preceding conversion.
To retrieve every conversion after the loop, we can collect the results in a list. all_minutes starts as an empty list. On each iteration, all_minutes.append(to_minutes(duration)) adds the conversion to the list and returns None. Assigning that return value to all_minutes would make the name refer to None.
1
2
3
4
5
6
| all_minutes = []
for duration in durations:
all_minutes.append(to_minutes(duration))
print(all_minutes)
all_minutes
|
1
2
3
4
| [0.5]
[0.5, 1.5]
[0.5, 1.5, 2.0]
[0.5, 1.5, 2.0]
|
A comprehension builds the same collection in one expression. In [to_minutes(duration) for duration in durations], the clause beginning with for takes each input in turn, and the expression before it computes the corresponding item of the new list.
1
| [to_minutes(duration) for duration in durations]
|
4.5 Functions as objects and arguments
What if we want to subtract 30 seconds from each duration instead of converting it to minutes? A helper function can take the calculation as an argument and use the same loop for either task. The name to_minutes refers to a function the loop can call for each duration. The expression to_minutes(90) evaluates to a single number.
An R function is a value that can be assigned to a name. convert <- to_minutes binds another name to the existing function. class() identifies to_minutes as a function and to_minutes(90) as numeric. With 90 as the argument, either name calls the same conversion.
1
2
3
4
5
| convert <- to_minutes
class(to_minutes)
class(to_minutes(90))
convert(90)
to_minutes(90)
|
1
2
3
4
| [1] "function"
[1] "numeric"
[1] 1.5
[1] 1.5
|
In apply_to_each(values, operation), values is the input vector and operation is the function to call on each element. With durations and to_minutes as the arguments, operation(values[i]) calls to_minutes(30) when i is 1. The loop stores 0.5 in results[1] and expects one number for each input.
1
2
3
4
5
6
7
8
| apply_to_each <- function(values, operation) {
results <- numeric(length(values))
for (i in seq_along(values)) {
results[i] <- operation(values[i])
}
results
}
apply_to_each(durations, to_minutes)
|
With subtract_30 as the operation, the same loop returns adjusted durations in seconds. For the first duration, 30 seconds minus 30 seconds gives 0.
1
2
3
4
| subtract_30 <- function(seconds) {
seconds - 30
}
apply_to_each(durations, subtract_30)
|
The argument function(seconds) seconds - 30 defines an anonymous function, one with no name, directly in the call. Its body is a single expression, so braces are optional. R also permits the shorthand \(seconds) seconds - 30. This gives the helper the same subtraction without first assigning it to subtract_30.
1
| apply_to_each(durations, function(seconds) seconds - 30)
|
The helper needs a function it can call for each duration. What happens if its second argument is instead the result of one conversion?
1
2
| # Deliberate error: a number where a function is needed
apply_to_each(durations, to_minutes(90))
|
1
| Error in operation(values[i]) : could not find function "operation"
|
Why does R report that it cannot find a function named operation? In this call, the parameter evaluates to 1.5, the result of to_minutes(90). At operation(values[i]), R looks for a function, skips the numeric value, and finds no function by that name in this example. Passing to_minutes gives the loop the function it needs.
A Python function is an object that can be assigned to another name. convert = to_minutes makes both names refer to the same function, as the identity test confirms. Its type is function. Calling it with 90 returns a float. An object that accepts a call is described as callable.
1
2
3
4
5
6
| convert = to_minutes
type(to_minutes)
type(to_minutes(90))
convert is to_minutes
convert(90)
to_minutes(90)
|
1
2
3
4
5
| <class 'function'>
<class 'float'>
True
1.5
1.5
|
In apply_to_each(values, operation), the loop calls operation(value) for each item and appends the returned value to results. With durations and to_minutes as the arguments, the first call is to_minutes(30). The first item in results is therefore 0.5 minutes. The helper returns the list after the loop.
1
2
3
4
5
6
7
8
| def apply_to_each(values, operation):
results = []
for value in values:
results.append(operation(value))
return results
apply_to_each(durations, to_minutes)
|
With subtract_30 as the operation, the same loop returns adjusted durations in seconds. Subtracting the integer 30 from each integer duration gives integer results.
1
2
3
4
5
| def subtract_30(seconds):
return seconds - 30
apply_to_each(durations, subtract_30)
|
lambda defines a function in an expression. In lambda seconds: seconds - 30, seconds is the parameter and the expression after the colon gives the return value. This supplies the subtraction directly, without first assigning it to subtract_30.
1
| apply_to_each(durations, lambda seconds: seconds - 30)
|
The helper needs a function it can call for each duration. What will the loop try to call if we pass to_minutes(90) as its second argument instead?
1
2
| # Deliberate error: a number where a function is needed
apply_to_each(durations, to_minutes(90))
|
1
| TypeError: 'float' object is not callable
|
Python evaluates to_minutes(90) before entering apply_to_each(), so operation receives the number 1.5. The error occurs when the loop tries to call that number. With apply_to_each(durations, to_minutes), the loop calls the conversion function for each duration.