Skip to course content
Free R data course

R Foundations for Data Analysis

Unit 02.07: Read the defaults before the description

Most of the time you are not asking what a function does. You are asking what it does when you do not tell it anything.

Read the defaults first

?mean opens the help page. It has a standard shape โ€” usage, arguments, details, value, examples โ€” and the two sections that answer real questions are Arguments and Examples. The examples are runnable, and example(mean) runs them.

The single most valuable habit is checking defaults, because a default is a decision the function made on your behalf. Whether missing values are dropped, whether sorting is ascending, whether a comparison is case-sensitive: all of these are defaults, and they vary between functions that feel similar.

This block reads the defaults of mean() straight out of the function rather than out of the documentation.


# The help page answers one question more often than any other:
# what does this function do by DEFAULT?

cat("Arguments of mean():\n")
print(args(mean.default))

cat("\nDefault of na.rm in mean():", formals(mean.default)$na.rm, "\n")

scores <- c(72, NA, 86, 91)
cat("mean(scores)             :", mean(scores), "\n")
cat("mean(scores, na.rm=TRUE) :", mean(scores, na.rm = TRUE), "\n\n")

# Defaults differ between functions that feel similar. Check, do not assume.
cat("sort() drops NA by default; length of sort(scores):", length(sort(scores)), "\n")
cat("but the input had length:", length(scores), "\n")
cat("\nEvery example on a help page is runnable: example(mean) executes them.\n")

The signature shows trim = 0 and na.rm = FALSE. That default is why mean(scores) returns NA while mean(scores, na.rm = TRUE) returns 83. Neither is wrong โ€” R is refusing to average around a hole unless you say so. The contrast at the end makes the point that defaults are not uniform: sort() drops NA without being asked, so a vector of length 4 comes back with length 3.

The mistake this prevents

The mistake is assuming na.rm = TRUE everywhere because it made an error go away once. It does not make the missingness go away; it just stops it being mentioned, and now the mean is over a different number of rows than you think.

Takeaway

Before using an unfamiliar function, read its argument defaults and run one of its examples. When you pass na.rm = TRUE, say in a comment how many rows that removes.