Australian National University · FACULTY OF STATISTICS

BIOL2001 Chap.5 Functions, the Apply Family and R Markdown

- one subject, every graph, every model, every mark
6 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 5 of 15 · BIOL2001

Functions, the Apply Family and R Markdown

Writing reusable code

A user-defined function lets one line stand for a task you repeat. This chapter dissects the anatomy of a function: its name, the function keyword, an argument list that can include defaults and the ellipsis, the body, and the value returned.

A worked example writes a density function for burrow counts with a default plot area.

Applying functions to data

The apply family runs a function over the parts of a structure without writing a loop. A figure computes apply() on a matrix of chick weights, with MARGIN = 1 returning one mean per chick and MARGIN = 2 one mean per week.

The chapter compares apply(), lapply() and sapply(), shows how anonymous functions and extra arguments are passed in, and warns that apply() coerces a data frame to one type.

Reproducible reports

It closes with R Markdown, which knits text, code and results into one document so that an analysis can be read, checked and rerun.

In this chapter

What this chapter covers

  • 01

    Anatomy of a user-defined function

  • 02

    Default arguments and the ellipsis

  • 03

    Anonymous functions

  • 04

    Margins of apply(): rows, columns or cells

  • 05

    List output from lapply, vectors from sapply

  • 06

    R Markdown and knitting

Worked example · free

Row and column means of a weight matrix

Q [4 marks]. A matrix X holds the weights in grams of three chicks (rows) over four weeks (columns): 12, 15, 19, 24; 10, 14, 17, 21; 11, 13, 18, 22. Give the results of apply(X, 1, mean) and apply(X, 2, mean). The practice weighting is assigned by AskSia and is not an official assessment.
Weights in grams of three chicks over four weeks.Weights in grams of three chicks over four weeks. apply(X, 1, mean) passes each row to mean and returns 17.5, 15.5 and 16.0; apply(X, 2, mean) passes each column and returns 11.0, 14.0, 18.0 and 22.3.week 1week 2week 3week 4chick 112151924chick 210141721chick 311131822MARGIN = 117.515.516.0MARGIN = 211.014.018.022.3
Weights in grams of three chicks over four weeks. apply(X, 1, mean) passes each row to mean and returns 17.5, 15.5 and 16.0; apply(X, 2, mean) passes each column and returns 11.0, 14.0, 18.0 and 22.3.
  • 1MARGIN = 1 passes each row to mean: 70/4 = 17.5 for chick 1.
  • 1Chicks 2 and 3 give 62/4 = 15.5 and 64/4 = 16.0, so the row result is 17.5, 15.5, 16.0.
  • 1MARGIN = 2 passes each column: 33/3 = 11.0, 42/3 = 14.0 and 54/3 = 18.0 for weeks 1 to 3.
  • 1Week 4 gives 67/3 = 22.3, completing the column result 11.0, 14.0, 18.0, 22.3.
apply(X, 1, mean) returns 17.5, 15.5 and 16.0, one value per chick, and apply(X, 2, mean) returns 11.0, 14.0, 18.0 and 22.3, one value per week. The margin fixes how many values come back; the function decides what each value is.
Sia tip — Before choosing MARGIN, ask how many answers you want: one per row means MARGIN = 1, one per column means MARGIN = 2.
Glossary

Key terms

User-Defined Function
A function you write yourself with the function keyword and assign to a name.
Default Argument
An argument given a value in the function definition, used when the caller supplies none.
Anonymous Function
A function written inline without a name, often passed directly to apply().
Ellipsis Argument
The three dots in an argument list, which accept any number of extra arguments.
Knitting
Rendering an R Markdown file, which runs its code and inserts the results into a finished report.
Margin
The apply() argument that chooses rows, columns or individual cells as the parts a function receives.
FAQ

Functions, the Apply Family and R Markdown FAQ

What does a function return if there is no return() statement?

It returns the value of the last expression evaluated in its body. A one-line function such as one that divides count by area therefore needs neither braces nor return(), while a longer function can use return() to make the returned value explicit.

When should I use sapply() instead of lapply()?

Both apply a function to each element of a list, vector or set of data frame columns. lapply() always returns a list, while sapply() simplifies the result into a vector or matrix where it can, which is usually more convenient for printing or further calculation.

Why is apply() risky on the rows of a data frame?

apply() coerces its input to a single data type before working. If a data frame mixes text and numbers, every value is turned into text, so numeric summaries fail or give wrong results. For column summaries of mixed data, sapply() over the columns is safer.

Study strategy

Assessment move

Write three small functions of your own, each with one default argument, and test each on a case you can check in your head. Then use apply() on a small matrix with both margins and predict the length of each result before running it. Knit an R Markdown file after every new chunk so errors surface one at a time.

To finish Part I, rebuild one of your workshop analyses as a single R Markdown document with a function, an apply() call and a short written conclusion, and knit it from a fresh session to prove it is reproducible.

Working through Functions, the Apply Family and R Markdown in BIOL2001? Sia is AskSia’s AI Statistics tutor — ask any BIOL2001 Functions, the Apply Family and R Markdown question and get a clear, step-by-step explanation grounded in how BIOL2001 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 46 of your Australian National University subjects - and 1,000+ Bibles across every Australian university.
Sia - your BIOL2001 tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works