0% found this document useful (0 votes)
28 views

K31 Imperativeprogrammierung

The document discusses imperative programming and structured programming in R. It defines imperative programming as a programming paradigm that uses statements to change a program's state. Structured programming uses control structures like loops and conditionals instead of jump statements. The document then examines different loop and conditional statements available in R.

Uploaded by

DunsScoto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

K31 Imperativeprogrammierung

The document discusses imperative programming and structured programming in R. It defines imperative programming as a programming paradigm that uses statements to change a program's state. Structured programming uses control structures like loops and conditionals instead of jump statements. The document then examines different loop and conditional statements available in R.

Uploaded by

DunsScoto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Advanced R

Chapter 3.1: Imperative Programming

Daniel Horn & Sheila Görz

Summer Semester 2022

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 1 / 50


Our plan for today

1 Definition of imperative programming

2 Structured programming

3 Modular programming

4 Debugging

5 Catching errors

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 2 / 50


Programming paradigms

Having learned about the components that make up R, we’re now


continuing with the actual act of programming.

The next lectures are all about three programming paradigms and their
realization in R:
Imperative programming,
Object-oriented programming,
Functional programming.
Today, we’re beginning with imperative programming.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 3 / 50


Definition of imperative programming

Definition of imperative programming

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 4 / 50


Definition of imperative programming

Definition of imperative programming

Imperative programming
Imperative programming is a programming paradigm that uses statements
that change a program’s state (...). An imperative program consists of
commands for the computer to perform. Imperative programming focuses
on describing how a program operates.a
a
Source: https://en.wikipedia.org/wiki/Imperative_programming Accessed June 6th, 2020.

Synonyms for imperative programming:


Procedural programming,
Algorithmic programming,
State-oriented programming.
Imperative programming is the oldest programming paradigm. It closely
resembles the execution of machine code on computers implemented
according to the Von-Neumann architecture.
Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 5 / 50
Definition of imperative programming

So, what does the definition actually mean?

The program code specifies what needs to be done and in what order
→ Sequence of instructions.
To this end, jump instructions (goto) and nested instructions (if) are
used.
Example: Computing factorials (pseudo code)
1 function(N)
2 i := 1
3 res := 1
4 if (i == N) goto 8
5 i := i + 1
6 res := res * i
7 goto 4
8 return res

Why is this only in pseudo code and not in R code? R doesn’t know explicit
jump instructions! → This original form of imperative programming can’t
be realized in R.
Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 6 / 50
Definition of imperative programming

Imperative programming in R
But, looping statements are part of imperative programming too. Thus, we
can now implement the computation of factorials imperatively in R:
faculty <- function(N) {
res <- 1
for(i in 1:N)
res <- res * i
return(res)
}

So, what’s not imperative programming then? If the source code only
specifies what is to be done, but not how. Example:

faculty <- function(N) { faculty <- function(N) {


if (N == 1) return(1) return(prod(1:N))
return(N * Recall(N - 1)) }
}

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 7 / 50


Structured programming

Structured programming

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 8 / 50


Structured programming

Structured programming and control structures

Structured programming is an advancement of imperative


programming.
Edsger W. Dijkstra’s publication ’Go To Statement Considered
Harmful’ (1968) is considered a pioneering work in this regard.
Dijkstra demanded abandoning the GOTO jump instruction.
Instead, control structures should be used.

Control structures
In imperative programming, control structures control the flow of a
computer program. A control structure is either a branching or a looping
statement.a
a
See: https://en.wikipedia.org/wiki/Control_flow Accessed June 6th, 2020.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 9 / 50


Structured programming

Control structures ain R

On the next couple of slides, we’re taking a look at the control


structures that R offers us:
Loops: for, while, repeat.
Branches/Conditionals: if, if/else.
Strictly speaking, these constructs aren’t actual control structures in R.
Recalling Paradigm 7: Everything happening in R is due to functions.
As such, control structures are also merely functions internally.
In addition to the constructs above, we’ll also cover the functions
ifelse() and switch().

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 10 / 50


Structured programming Loops

Loops - what are they for?

Loops repeat an instruction block until ...


... a predefined number of iterations has been reached (for),
... the instruction block has been executed for every element of a given
set (for),
... a termination condition has been met (while, repeat).
Loops process program code iteratively. Every loop can be rewritten as
an equivalent recursive program.
Loops can be nested.
Loops terminating due to meeting certain conditions (while, repeat)
could potentially run indefinitely. This is not possible when using the
for loop.
In R, loops are also just functions. Their data type is special and
their return value is invisible(NULL).

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 11 / 50


Structured programming Loops

Loops - special commands


The ’natural course’ of a loop can be influenced with two commands:
break and next.
break immediately terminates the loop.
next causes the loop to directly jump into the next iteration.
These control commands always only affect the calling loop. Other loops
(e.g. in the case of nested loops) are not affected.

for (i in 1:3) { for (i in 1:3) {


if (i == 2) next for (j in 1:3) {
print(i) if (j == 2) break
} print(c(i, j))
}
## [1] 1 }
## [1] 3
## [1] 1 1
## [1] 2 1
## [1] 3 1

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 12 / 50


Structured programming Loops

The for-loop I

The number of iterations of a for-loop is predefined and finite.


The syntax of a for-loop is as follows: for (var in seq) expr.
Where:
var is an index,
seq is either a vector (incl. lists and expressions), a pairlist or NULL,
expr is an instruction. When using multiple instructions, they have to
be enclosed by curly brackets.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 13 / 50


Structured programming Loops

The for-loop II

The seq vector can be interpreted in three different ways:


seq is often times an index vector. E.g: for (i in 1:length(x)).
seq can, however, also be a vector containing elements that are iterated
themselves. Many programming languages have a dedicated loop for
this, the foreach-loop. In R, this loop is accounted for in the for-loop.
Though used infrequently, it’s possible to iterate over a vector’s names.

x <- c(10, 20) for (i in x) names(x) <- c("a", "b")


for (i in 1:length(x)) print(i) for (i in names(x))
print(x[i]) ## [1] 10 print(x[i])
## [1] 10 ## [1] 20 ## a
## [1] 20 ## 10
## b
## 20

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 14 / 50


Structured programming Loops

The for-loop III

seq is evaluated at the first call of the loop and can’t be modified by
the function body at a later point. Thus, no infinite loops can occur:
for (i in 1:2) { for (i in x)
print(i) x <- c(x, 0)
i <- i - 1 x
} ## a b
## [1] 1 ## 10 20 0 0
## [1] 2

In particular, it’s not possible to increment the iteration counter inside


the function body to skip an iteration. This requires using next.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 15 / 50


Structured programming Loops

The for-loop IV

As already mentioned, the for-loop returns invisible(NULL).


Additionally, the latest value of var remains:
i
## [1] 20

Common mistake when using for-loops: An index vector running from


1 to 0. Since the length of y is zero, 1:length(y) is evaluated to
c(1, 0) which has length 2.

y <- numeric(0) for (i in y)


for (i in 1:length(y)) print("Hello")
print("Hello")
## [1] "Hello"
## [1] "Hello"

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 16 / 50


Structured programming Loops

The while-loop I

The syntax of the while-loop is while (cond) expr where expr


(loop body) must be enclosed by curly brackets if it contains more
than one instruction.
The while-loop iterates as long as cond is evaluated to FALSE.
R only offers the ’pre-test’ while-loop which checks the condition
before executing its body. A ’post-test’ do-while-loop does not exist
in R.
while-loops can be used to create infinite loops.
Simple example:
while (TRUE) x <- x + 1

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 17 / 50


Structured programming Loops

The while-loop II

As we have already seen in the chapter on data types, numbers can be


interpreted as logical values. In this case, only zero is evaluated as
FALSE. Thus, this also works:
x <- 3
while (x) {
print(x)
x <- x - 1
}
## [1] 3
## [1] 2
## [1] 1

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 18 / 50


Structured programming Loops

The while-loop III

If the condition contains an NA, an error occurs.


If the condition contains multiple logical expressions, only the first is
used and a warning is issued.

while(NA) print(1) while(c(FALSE, TRUE)) print(1)


## Error in while (NA) print(1): ## Warning in while (c(FALSE, TRUE))
missing value where TRUE/FALSE print(1): the condition has length >
needed 1 and only the first element will be
used

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 19 / 50


Structured programming Loops

The repeat-loop

The repeat-loop iterates as long as break is called - as such, it’s an


infinite loop by default.
Contrary to other programming languages, there is no
repeat-until-loop in R that allows specifying an explicit termination
condition.
The syntax of the repeat-loop is:
repeat {
expr1
if (cond) break
expr2
}

In general, either expr1 or expr2 exists, resulting in a pre-test or


post-test loop respectively. It’s also possible to have a break inside
the code block.
The repeat-loop is very similar to the while-loop.
Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 20 / 50
Structured programming Loops

Vectorization

In R, loops are only seldomly truly necessary. They are needed, for
example, when an iteration depends on previous ones.
Most loops can be rewritten in a functional way → apply.
Even though the apply family is no longer significantly faster than a
loop since R version 3.4.0, it still offers certain advantages, e.g.
concerning parallel computing. More on this in the chapter on
functional programming.
Vectorizing program code makes it faster, nicer and more efficient
than loops and applys. Many R functions already work in a vectorized
way. Thus, before using loops, always ask yourselves if they are truly
necessary.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 21 / 50


Structured programming Conditionals

Conditionals - what are they for?

A conditional statement specifies which code block (possibly amongst


many) should be executed.
Conditionals occur in slightly different use cases:
A code block is only to be executed if a certain condition is met (if).
Depending on the result of an evaluation, different code blocks are to
be executed (if/else and switch())
Conditional statements can be nested.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 22 / 50


Structured programming Conditionals

The if-construct

The if-construct first evaluates a condition. If the condition is


evaluated to TRUE (or to something that can be interpreted as such),
the statement conditioned upon is executed, otherwise not.
The syntax is: if (cond) expr where expr must be enclosed by
curly brackets when containing multiple instructions.
The if-construct returns the lastly evaluated expression. Thus, the
following two calls are identical if the condition is TRUE:
if (any(x <= 0)) y <- log(1 + x)
y <- if (any(x <= 0)) log(1 + x)

If the condition is evaluated to FALSE, the if-call returns NULL. In this


case, the two calls above are not identical, since the variable y is no
longer assigned in the first version.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 23 / 50


Structured programming Conditionals

The if/else-construct I

Contrary to the simple if-conditional, the if/else-construct results


in the execution of exactly one block of code.
The syntax is: if (cond) expr1 else expr2 where curly brackets
are required when the statements contain multiple instructions.
cond must be a single logical value and can’t be an NA. If the length
of cond is greater than 1, only the first element will be used.
Since the else is optional, one should be mindful of not placing it at
the beginning of a new line. Otherwise, the if represents a complete
call and the parser will not process the else anymore.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 24 / 50


Structured programming Conditionals

The if/else-construct II

These notations are allowed:

if (cond) expr1 else expr2 if (cond) {


expr1
} else {
expr2
}

These are not:


if (cond) expr1
else expr2

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 25 / 50


Structured programming Conditionals

The if/else-construct III

if/else-constructs can be nested.

This kind of nesting is messy: This one is much nicer:


if (cond1) { if (cond1) {
expr1 expr1
} else { } else if (cond2) {
if (cond2) { expr2
expr2 } else if (cond3) {
} else { ...
... } else {
} exprn
} }

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 26 / 50


Structured programming Conditionals

The ifelse() function I

The if function can only evaluate one condition at a time.


In theory, this would necessitate constructions such as:
x <- runif(5)
for (i in 1:length(x))
if (x[i] < 0.5) x[i] <- x[i] - 1 else x[i] <- x[i] + 1

Fortunately, R offers a vectorized version of the if/else construct.


The syntax is: ifelse(test, yes, no). test denotes the condition;
yes is executed for the elements fulfilling test while no is executed
for the remaining elements.
This leads to a call equivalent to the one above:
x <- runif(5)
x <- ifelse(x < 0.5, x - 1, x + 1)

ifelse() functions can also be nested:


ifelse(test1, yes1, ifelse(test2, yes2, no))

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 27 / 50


Structured programming Conditionals

The ifelse() function II

If all elements of test are either TRUE or FALSE, then subsequently


only yes or no are evaluated respectively.
If test contains TRUE as well as FALSE, then yes and no are
evaluated for all elements.
This behavior has consequences:
set.seed(1503)
y <- runif(5, -1, 1)
ifelse(y > 0, log(y), log(-y))
## Warning in log(y): NaNs produced
## Warning in log(-y): NaNs produced
## [1] -1.77404080 -1.57835554 -0.23615951 -0.07766003 -1.17621281

These warnings are issued because in some cases logarithms of


negative numbers are calculated - even though they aren’t needed in
the end anyway.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 28 / 50


Structured programming Conditionals

The switch() function I

switch() is another function to realize conditional statements in R.


Syntax: switch(statement, expr) where ...
... statement is an R statement which should be evaluated to either a
number or a character.
... expr is a set of (named) objects out of which the appropriate object
gets evaluated.
switch() does not work in a vectorized way. statement may only
have length 1.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 29 / 50


Structured programming Conditionals

The switch() function II

switch() has two different functionalities:


1. statement is evaluated to a number.
The returned number is rounded down to the next integer x.
The x-th object from expr is evaluated and returned:

switch(2, sum(1:2), mean(1:2), sd(1:2)) switch(sample(3, 1), "A", "B", "C")

## [1] 1.5 ## [1] "B"

If x is too small or too large, then NULL is returned invisibly.

switch(3, "A", "B")

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 30 / 50


Structured programming Conditionals

The switch() function III

2. statement is evaluated to a character.


If statement is a character, then (almost) all objects from expr
must be known.
switch() evaluates the object from expr whose name matches
exactly. There is no partial matching in this case.
switch("number", word = "Hello", number = 1)
## [1] 1
switch("number", word = "Hello", numbe = 1)

If an object has no name, then this one is set as the default and
returned when statement matches no other object.
switch("letter", word = "Hallo", number = 1, "Neither")
## [1] "Neither"

Two unnamed arguments result in an error.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 31 / 50


Modular programming

Modular programming

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 32 / 50


Modular programming

Subroutines

Pure imperative programming consists of a sequence of commands and


control structures. When writing longer programs, it can be reasonable to
divide them into smaller chunks, i.e. so-called subroutines.
Definition: Subroutine
A subroutine is a sequence of program instructions that performs a specific
task, packaged as a unit. This unit can then be used in programs wherever
that particular task should be performed. a Usually, they fulfill simple
recurring tasks. Subroutines depend on parameters and usually have a
return value. In R, functions correspond to the subroutine term.
a
Source: https://en.wikipedia.org/wiki/Subroutine Accessed June 6th, 2020.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 33 / 50


Modular programming

Example: Subroutines
x <- seq(-5, 10, length.out = 100)

We’re calculating a trimmed mean:

x2 <- x[abs(x) > 9] x2 <- x[abs(x) > 7] x2 <- x[abs(x) > 5]


mean(x2) mean(x2) mean(x2)

## [1] 9.545455 ## [1] 8.560606 ## [1] 7.575758

This looks much nicer when using a subroutine:

trimMean <- function(x, val) { trimMean(x, 9)


x2 <- x[abs(x) > val]
mean(x2) ## [1] 9.545455
}
trimMean(x, 7)

## [1] 8.560606

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 34 / 50


Modular programming

What are subroutines for?

Subroutines describe functions that fulfill specific recurring tasks.


Subroutines can be called at numerous locations in the program code -
whenever the respective task needs to be fulfilled.
Using subroutines offers many advantages:
It’s much easier to maintain multiple short and meaningful code
segments than one single long (error-prone) program
Subroutines can depend on parameters and thus bundle similar
behavior. This leads to avoiding copy-paste style code.
→ Always use subroutines for recurring tasks inside your programs.
Subroutines – just like control structures – are a given in more modern
programming languages.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 35 / 50


Debugging

Debugging

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 36 / 50


Debugging

Debugging - Searching for errors interactively

Few things are as frustrating as writing a long function by yourself and


having it result in an error upon execution without actually knowing
where and why this error occurred.
To this end, R offers multiple debugging functions that can be used to
look inside trouble-causing functions and to hopefully locate the error.
Since debugging is an interactive process, it’s hard to depict on slides.
That’s why we will only take a look at the theoretical aspects of
debugging functions here. Applications and examples will be discussed
during the exercises.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 37 / 50


Debugging

The process of debugging I

When an error occurs, it’s important to approach it systematically. These


four steps should help:

1. Recognize an error
As trivial as this step might seem, it’s still essential.
Recognizing errors doesn’t simply consist of realizing an error
occurred. It also means to detect results/outputs of your function
thought to be impossible.
2. Make the error reproducible
Create a minimal example that produces the error.
Be mindful of using as few lines of code as possible and to reduce the
runtime of your example to a minimum.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 38 / 50


Debugging

The process of debugging II

3. Find the origin of the error


This is what the next couple of slides will be about.
R offers multiple possibilities for this.
4. Fix the error and check if it’s really gone
This concerns finding out how to fix the error and all the eventualities
that may have caused it.
Use different parameters to check if the error is actually fixed.
Automated testing (E.g. using the package testthat) helps with this.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 39 / 50


Debugging

Debugging tools - traceback() I


If an error occurs, R generates an invisible variable .Traceback which
is used by the function traceback().
Upon encountering an error, the function traceback() displays the
so-called ’call stack’.
The call stack shows the sequence of function calls that has led to the
respective error.
Let’s consider the following example: Here, multiple functions are
nested. In the innermost layer, we are trying to add a letter and a
number.
f <- function(a) g(a)
g <- function(b) h(b)
h <- function(c) i(c)
i <- function(d) "a" + d

f(10)

## Error in "a" + d: non-numeric argument to binary operator

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 40 / 50


Debugging

Debugging tools - traceback() II

.Traceback now contains a pairlist with the following entries:


.Traceback

[[1]]
[1] "i(c)"

[[2]]
[1] "h(b)"

[[3]]
[1] "g(a)"

[[4]]
[1] "f(10)"

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 41 / 50


Debugging

Debugging tools - traceback() III

traceback() packages the same information in a more pleasant way:


traceback()

4: i(c) at #1
3: h(b) at #1
2: g(a) at #1
1: f(10)

What do we make of this?


The traceback should be read from the bottom to the top.
The sequence starts at the outermost function call (at the bottom) and
leads up to the final function call (at the top) that caused the error.
’at #1’ means that the error occurred in the function’s first line.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 42 / 50


Debugging

Debugging tools - trace()


trace() is a powerful tool offering a lot of functionality.
We’re only showing the most simple use case. For more, see ?trace.
In the most simple case, a function (as a character string) is passed
to trace().
Then, each time this function is called explicitly or implicitly (inside of
other functions), a notification is printed to the console.
Tracing can be terminated by calling untrace().
Example:
trace("sum")
hist(rnorm(100)) # hist() calls sum() multiple times

## trace: sum
## trace: sum
## trace: sum

untrace("sum")

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 43 / 50


Debugging

Debugging tools - browser() I

The command browser() is placed inside the function that is


supposed to be debugged.
When now calling the respective function, the execution halts upon
encountering browser().
Now, we are inside the function’s environment and can work
interactively inside the function. For example, we can inspect the
current values of variables by typing their names in the console.
While browsing, R functions as usual, only that everything that is being
called or defined happens inside the function that we’re debugging.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 44 / 50


Debugging

Debugging tools - browser() II

Some console commands have a special meaning while browsing:


n (next): This command executes the next line of code and then halts
once more.
s (step into): Works just like n. If the next stop is a function, we’re
then stepping into this function and are able to inspect it.
f (finish): Terminates the execution of the current loop or function.
c (continue): Executes the next lines of code and halts again upon
encountering the next browser().
Q (quit): Quits debugging and the function without fully executing it.
If an object shares its name with one of the letters above, then
additional steps must be taken to inspect it during the interactive
mode. In this case, functions such as print() or get() might help
depending on the context.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 45 / 50


Debugging

Debugging tools - browser() III

RStudio users have it easy: Setting browser() is not necessary there,


because it’s possible to set break points (by clicking left to the line
number). Furthermore, a tool bar appears automatically that offers the
same functionality as the commands above.
Example:
myFun <- function(x) { myFun(c(2, 4, 8))
Called from: myFun(c(2, 4, 8))
c <- 0 Browse[1]> x
for(i in 1:3) { [1] 2 4 8
browser() Browse[1]> i
[1] 1
c <- c + x[i] Browse[1]> n
} debug at #5: c <- c + x[i]
return(c) Browse[2]> c
Called from: myFun(c(2, 4, 8))
} Browse[1]> get("c")
[1] 2
Browse[1]> f
[1] 14

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 46 / 50


Debugging

Debugging tools - debug()

The function debug() works just like browser() - only that the
function is not halted at a specific line but at the first.
Using n, it’s then possible to inspect each line of code.
It’s used like this:
debug("median")
median(1:10)
undebug("median")

browser() and debug() are special cases of the trace() function


which we have already come across in its simplest use case.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 47 / 50


Catching errors

Catching errors

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 48 / 50


Catching errors

Error handling - The try() function I

Usually, it’s reasonable for a program to abort upon encountering an


error.
There are, however, some situations in which it may be desirable to
continue the execution of code despite the occurrence of errors.
For example, consider a long simulation in which single parameter
configurations can’t be evaluated due to numeric issues. Generally,
these configurations are not known in advance and as such, can’t be
explicitly intercepted by an if conditional.
Solution: Use try(). This function tries evaluating its argument. If
this doesn’t work, it returns the error message (invisibly) without
aborting the function’s execution.

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 49 / 50


Catching errors

Error handling - The try() function II


Example:
try(log(10)) fun <- function(x) {
## [1] 2.302585 try(log(x))
return(10)
}
try(log("a")) fun("a")
Error in log("a") : non-numeric
argument to mathematical function Error in log(x) : non-numeric
argument to mathematical function
try(log("a"), silent = TRUE) [1] 10

This way, results of failed calculations can be imputed:


fun2 <- function(x) {
tmp <- try(log(x), silent = TRUE)
if (is.numeric(tmp)) return(tmp) else return(Inf)
}

fun2(10) fun2("a")
## [1] 2.302585 ## [1] Inf

Daniel Horn & Sheila Görz Advanced R Summer Semester 2022 50 / 50

You might also like