22  Help and Documentation

NoteSession at a Glance

Total core time: ~80 minutes (about 1.3 hours). Unlike the other sessions in this course, this one is a reference guide, not a linear walkthrough. Skim it once now so you know what is here, then come back to specific sections whenever you hit an error or get stuck during another session.

Section Time Type
Getting Help Inside R ~10 min Reference
Common Error Messages ~20 min Reference
Warnings vs Errors ~5 min Reference
Useful Functions for Debugging ~10 min Reference
Online Resources ~10 min Reference
Course Method Map ~5 min Reference
Comprehension Check ~10 min Self-test
Common Pitfalls When Getting Help ~10 min Reading

If you are short on time, focus on Common Error Messages: those five error and warning patterns (especially the “fitted probabilities numerically 0 or 1” warning and the na-debug chunk) are the ones you are most likely to meet elsewhere in this course.

TipHow to Use the Code in This Session

Every code chunk below is written so you can copy it into your R console (or an R script) and run it yourself, in the order shown. Where you see a “Run It Yourself” box, stop and run the code above it before reading the explanation that follows.

22.1 When Do You Use This?

Tip

You are halfway through an analysis and get an error message you don’t understand. Or you can’t remember the exact arguments for a function. This session is your reference guide: how to get help inside R, how to read error messages, how to find the right function for a task, and where to turn when you’re stuck.

Before working through this session, ask learners to find (or recall) an error message they have personally encountered in this course - in their console history, a script, or their memory. Keep it visible. As you go through “Common Error Messages” below, check whether it matches one of the five patterns covered, and if not, diagnose it together using the ?, help.search(), and debugging-function workflow from the first two sections.

22.2 Learning Objectives

After completing this session you will be able to:

  • Use R’s built-in help system to look up any function
  • Interpret common R error and warning messages
  • Search for packages and functions you don’t know the name of
  • Find the right online resources for R and statistics questions
  • Locate the relevant session in this course for any statistical method

22.3 Getting Help Inside R

Estimated time: ~10 minutes (Reference)

22.3.1 The ? Operator and help()

# Access help for a function you know the name of
?mean
help(mean)

# Access help for an operator
?`+`

# Access help for a whole package
help(package = "survival")

22.3.2 Help When You Don’t Know the Name

# Fuzzy search: returns all help pages matching the keyword
??regression
help.search("regression")

# Find a function by name fragment
apropos("glm")

22.3.3 Reading a Help Page

Every R help page has the same structure:

Section What it tells you
Description What the function does in one sentence
Usage Function signature: all arguments with defaults
Arguments What each argument expects
Value What the function returns
Examples Copy-paste these first to understand the function
See Also Related functions: often more useful than the main function

Tip: Jump straight to Examples when learning a new function. Run them interactively to see what the function does before applying it to your own data.

22.4 Common Error Messages

Estimated time: ~20 minutes (Reference)

22.4.1 Object Not Found

Error in plot(my_data) : object 'my_data' not found

Cause: The object does not exist in your environment. You may have forgotten to run the line that creates it, or you misspelled the name. R is case-sensitive: mydata - MyData.

Fix: Check ls() to list all objects in your environment. Re-run the code that creates the object.

22.4.2 Unexpected Symbol / Unexpected Input

Error: unexpected ')' in "mean(x, na.rm = TRUE))"

Cause: A syntax error: mismatched brackets, a missing comma, or an unclosed string.

Fix: Count your opening and closing brackets. In RStudio, click inside the bracket to see its matching partner highlighted.

22.4.3 Package Not Found

Error in library(ggplot2) : there is no package called 'ggplot2'

Cause: The package is not installed.

Fix:

install.packages("ggplot2")   # install once
library(ggplot2)               # load every session

22.4.4 NA / NaN Warnings

Warning message: NAs produced by coercion

Cause: R cannot convert a non-numeric value (e.g., "N/A", ".", or "") to a number. These become NA.

Fix: Check what non-numeric strings are in your column before coercing:

x <- c("1", "2", "N/A", "4")
which(is.na(as.numeric(x)))   # which elements became NA?
Warning in which(is.na(as.numeric(x))): NAs introduced by coercion
[1] 3
x[is.na(as.numeric(x))]       # what are they?
Warning: NAs introduced by coercion
[1] "N/A"
TipRun It Yourself

Both lines trigger Warning: NAs introduced by coercion - that warning is the clue, not a separate problem to chase down. The first line returns [1] 3: element 3 of x became NA when coerced to numeric. The second line shows you why: [1] "N/A" - the string "N/A" is not a number R recognises, so as.numeric() silently turns it into NA and raises this warning. This two-line pattern - “which positions became NA?” then “what were they originally?” - is the fastest way to track down a coercion warning in your own data.

22.4.5 Subscript Out of Bounds

Error in x[[5]] : subscript out of bounds

Cause: You are trying to access an element that does not exist (e.g., the 5th column of a data frame that only has 4 columns).

Fix: Check dimensions: dim(df), length(x), nrow(df), ncol(df).

22.4.6 Factor Level Mismatch

Error in model.frame.default : factor has new levels: XYZ

Cause: You are predicting with new data that contains a factor level not seen during model fitting.

Fix: Ensure new data factor levels match training data. Use droplevels() or re-encode factor levels consistently.

22.5 Warnings vs Errors

Estimated time: ~5 minutes (Reference)

Message type Meaning Action needed?
Error R stopped: no result produced Yes: must fix
Warning R produced a result, but something may be wrong Check: often important
Message Informational only (e.g., from packages loading) No: usually safe to ignore

Key warning to never ignore:

Warning message: In glm.fit() : fitted probabilities numerically 0 or 1 occurred

This means your logistic regression has complete separation: a predictor perfectly separates outcomes. The model is unreliable; see Section 13.1.

22.6 Useful Functions for Debugging

Estimated time: ~10 minutes (Reference)

# What is in my environment?
ls()

# What class is this object?
class(my_object)
typeof(my_object)

# What is the structure?
str(my_data)
glimpse(my_data)

# Check for missing values
sum(is.na(my_data))
colSums(is.na(my_data))

# View first/last rows
head(my_data)
tail(my_data)

# Check column names and types
names(my_data)
sapply(my_data, class)

22.7 Online Resources

Estimated time: ~10 minutes (Reference)

22.7.1 Finding Answers

Resource Best for URL
Stack Overflow Specific error messages and code questions stackoverflow.com/questions/tagged/r
RDocumentation Searchable R function and package documentation rdocumentation.org
CRAN Task Views Finding the right package for a statistical task cran.r-project.org/web/views/
Posit Community Tidyverse and RStudio questions community.rstudio.com
R-bloggers Tutorials and use cases r-bloggers.com

22.7.2 Asking Good Questions

When posting to Stack Overflow or asking a colleague, always provide a minimal reproducible example (reprex):

library(reprex)
reprex({
  x <- c(1, 2, NA, 4)
  mean(x)               # what did you get?
  mean(x, na.rm = TRUE) # what do you expect?
})

A reprex is a small, self-contained snippet of code that demonstrates the problem. Remove anything not essential to reproducing the error.

22.8 Course Method Map

Estimated time: ~5 minutes (Reference)

The table below maps every statistical method covered in this course to its session. Use this to quickly navigate when you need to recall a method.

Method Session
Setting up R and packages Section 1.1
Describing data, distributions, normality Section 2.1
Sampling and estimation Section 3.1
Hypothesis testing framework Section 4.1
t-tests Section 5.1
Non-parametric tests Section 6.1
ANOVA Section 7.1
Categorical data and chi-square Section 8.1
Power and sample size Section 9.1
Correlation and association Section 10.1
Linear regression Section 11.1
Multiple regression Section 12.1
Logistic regression Section 13.1
Model building and diagnostics Section 14.1
Missing data imputation Section 15.1
Mixed models Section 16.1
Survival analysis Section 17.1
Causal inference and DAGs Section 18.1
Mendelian randomisation Section 19.1
Statistical decision guide Section 20.1
Clinical research methods Section 21.1

22.9 Comprehension Check

Estimated time: ~10 minutes (Self-test)

These questions revisit the error and warning patterns from earlier in the session, but ask learners to explain them rather than just recognise them. Encourage learners to answer from memory first, then check the relevant section above before reading the model answer - the goal is to practise diagnosing an error from the message alone, the same skill that matters when a real error appears in their own analysis.

  1. You run lm(y ~ x, data = mydata) and get Error: object 'y' not found. What are two likely causes?
  2. What is the difference between an R error and a warning? Give an example of a warning you should not ignore.
  3. You want to do a survival analysis but don’t know which function to use. How would you search for relevant functions in R?
  4. A colleague’s code throws Error in model.frame : factor has new levels. What does this mean, and how would you fix it?
  5. You get a message Warning: 152 rows removed due to missing values. Should you be concerned? What would you check?
    1. The column y does not exist in mydata: check column names with names(mydata). A common cause is a typo or capitalisation mismatch (R is case-sensitive: Yy). (b) The object mydata itself does not exist in the environment; run ls() to check, and re-run the code that creates mydata.
  1. An error stops execution and produces no output; you must fix it before R will continue. A warning means R completed the computation but flagged something potentially problematic. Warnings you should not ignore include: fitted probabilities of 0 or 1 in logistic regression (complete separation); NAs introduced by coercion (unexpected missing data); rank-deficient fits (collinearity in regression). A warning you can usually ignore: package 'X' was built under R version Y.Z: just means the package was built with a slightly different R version.
  2. Two approaches: (1) help.search("survival") or ??survival searches all help pages for the keyword; (2) Look at the CRAN Task View for Survival Analysis at https://cran.r-project.org/web/views/Survival.html: this lists all packages and key functions for survival analysis. The survival package and its Surv(), survfit(), coxph() functions are the standard starting point.
  3. The model was trained on data where a factor had certain levels (e.g., race: “White”, “Black”), but the new data contains a level not seen during training (e.g., “Other”). R cannot encode this new level. Fix: ensure all factor levels in new data are present in the training data; use levels(new_data$race) <- levels(training_data$race) or use consistent factor encoding before splitting into train/test sets.
  4. Yes, be concerned. 152 missing values could mean: (a) a column has systematic missingness: check colSums(is.na(df)) to identify which variable; (b) the missing data is not missing at random (MCAR); if missingness is related to the outcome or exposure, complete-case analysis will be biased. Steps: identify which variables have missing data, check whether missingness is associated with the outcome, and consider whether imputation is needed (see Section 15.1).

22.10 Common Pitfalls When Getting Help

Estimated time: ~10 minutes (Reading)

Warning

Posting an incomplete question. The most common reason a Stack Overflow question goes unanswered is that it lacks a reproducible example. Always include: the exact error message, the R version and key package versions, and a minimal dataset that demonstrates the problem (use dput() or a built-in dataset).

Searching for the wrong thing. Error messages in R are often generic. Search for the function name and package name alongside the error text, not the error alone. For example: “lme4 singular fit random effects” is a better search than “model failed to converge.”

Copying code without understanding it. If you paste a solution and it works, spend 60 seconds asking why. Change one thing to confirm your mental model. Copy-paste dependency is the main reason R skills don’t compound.

Not checking the package version. Many Stack Overflow answers are outdated. Always confirm that the answer applies to your version (packageVersion("pkg")). Behaviour changes across versions, especially for dplyr, ggplot2, and tidymodels.

Skipping ?function_name before asking. The help page often contains a working example that answers the question. Always check the Examples section at the bottom of the help page first.

22.11 Further Reading

22.12 How to Cite This Course

If you use this course in your teaching or research, please cite it:

Suleman, S. (2026). Basic Statistics for Researchers. Zenodo. https://doi.org/10.5281/zenodo.20672940

DOI

BibTeX:

@misc{suleman2026basicstats,
  author    = {Suleman, Sufyan},
  title     = {Basic Statistics for Researchers},
  year      = {2026},
  publisher = {Zenodo},
  doi       = {10.5281/zenodo.20672940},
  url       = {https://doi.org/10.5281/zenodo.20672940}
}
Grolemund, Garrett. 2015. Hands-on Programming with r. O’Reilly Media. https://rstudio-education.github.io/hopr/.
Wickham, Hadley. 2019. Advanced r. 2nd ed. Chapman & Hall/CRC. https://adv-r.hadley.nz/.