Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

1Objectives

By the end of this lesson you will be able to:

  1. Recognize the eight R errors and warnings students learning R for statistics hit most often.

  2. Diagnose the cause behind each message, not just the symptom.

  3. Fix each one with a small, concrete change to your code.

  4. Read any future R error the same systematic way: what does R say is wrong, and where.

2Errors are not a sign you did something wrong

Every R user — instructors included — sees these same eight messages constantly. An error is R telling you exactly where it got stuck, which makes it the single best debugging clue you have, not a signal to start over. Every message on this page is real R 4.5.2 output, produced by actually running the broken code shown — not retyped from memory — so what you see here is exactly what you’ll see on your own screen.

suppressMessages({library(mosaic); library(BSDA)})
set.seed(2200)
survey <- read.csv("data/survey_sim.csv")

3The eight errors, at a glance

#Error/warningUsual cause
1object '...' not foundTypo in a variable/column name, or using a bare column name outside a formula
2could not find function "..."Forgot library(mosaic) (or BSDA) this session
3non-numeric argument to binary operatorDoing arithmetic between a numeric column and a text/factor column
4object '...' not found (inside a formula)data = points at the wrong data frame — the column you named lives somewhere else
5Invalid formula typePassed a $-extracted vector where a function wanted a ~ formula
6argument is not numeric or logical: returning NAA numeric-looking column imported as text/character because of one contaminated cell
7cannot open the connection / No such file or directoryTypo’d file name, or wrong working directory
8there is no package called '...'Typo’d package name, or the package genuinely isn’t installed

Each is worked through below with the real broken code, the real message, and a real fix.

41. object '...' not found

mean(sleep_hors)
Error : object 'sleep_hors' not found

Cause: a typo — sleep_hors instead of sleep_hours — used as a bare name with no $ and no data = . R has no idea where to look for a column called sleep_hors, so it looks in your regular workspace, doesn’t find it there either, and stops.

Fix: spell the column name correctly and reach into the data frame with $ (or use it inside a formula with data = , Section 4’s territory):

mean(survey$sleep_hours)
[1] 6.7875

52. could not find function "..."

favstats(~sleep_hours, data = survey)
Error in favstats(~sleep_hours, data = survey) : 
  could not find function "favstats"

Cause: favstats() lives in the mosaic package (L05), and this session never ran library(mosaic) — maybe the kernel restarted, or the library() line further up the notebook was never executed.

Fix: run library(mosaic) (and library(BSDA)) once at the top of your session, before any line that uses a function from either package:

library(mosaic)
favstats(~sleep_hours, data = survey)
 min  Q1 median    Q3 max   mean       sd   n missing
 3.9 6.1    6.8 7.425 9.1 6.7875 1.012241 120       0

63. non-numeric argument to binary operator

survey$sleep_hours + survey$pet
Error in survey$sleep_hours + survey$pet : 
  non-numeric argument to binary operator

Cause: + (and every other arithmetic operator) only works between numbers. sleep_hours is numeric, but pet is text (“Cat person”, “Dog person”, “Neither”) — R has no defined meaning for 6.7 + "Cat person", so it refuses outright rather than guess.

Fix: this usually means you reached for the wrong tool — you likely wanted to compare sleep_hours across the groups in pet, which is exactly what the mosaic formula interface is for (L05L07), not raw arithmetic between the two columns:

favstats(sleep_hours ~ pet, data = survey)
         pet min    Q1 median   Q3 max     mean        sd  n missing
1 Cat person 4.2 6.075   6.65 7.20 9.1 6.687500 1.0268667 40       0
2 Dog person 3.9 6.050   6.80 7.55 8.8 6.763636 1.0660352 55       0
3    Neither 5.3 6.600   7.00 7.50 8.6 7.000000 0.8631338 25       0

74. Wrong data = (right column name, wrong data frame)

mini <- survey[, c("student_id", "pet", "class_year")]
favstats(exam_score ~ pet, data = mini)
Error in eval(x, data, env) : object 'exam_score' not found

Cause: the same object '...' not found message as error #1, but from a different mistake — exam_score is spelled correctly, but mini (the data frame actually passed to data = ) never had that column to begin with; it was dropped by the [, c(...)] selection above.

Fix: point data = at a data frame that actually contains every column your formula names — here, the original survey:

favstats(exam_score ~ pet, data = survey)
         pet  min   Q1 median    Q3  max     mean        sd  n missing
1 Cat person 39.7 56.3  63.05 68.35 80.7 61.87000  9.356917 40       0
2 Dog person 40.0 58.0  62.20 68.45 86.1 63.17273  9.320357 55       0
3    Neither 42.2 49.8  55.60 60.20 84.1 57.47200 10.719084 25       0

85. $ vs. formula: passing a vector where a function wants ~

gf_histogram(survey$sleep_hours)
Error : Invalid formula type for gf_histogram.

Cause: every gf_* plotting function (L07) expects a formula (~sleep_hours) plus a separate data = argument — not a plain vector pulled out with $. survey$sleep_hours is valid R (it’s the exact syntax error #1’s fix used), just not the shape gf_histogram() is built to accept.

Fix: switch back to the formula + data = pattern every mosaic and ggformula function shares:

gf_histogram(~sleep_hours, data = survey)

Plots without error — the identical picture as L07’s sleep-hours histogram, because it’s the identical underlying data.

96. Factor/character vs. numeric: a column that imported as text

Say one cell of a numeric-looking survey column got typed as "5 stars" instead of 5 before the file was saved. Simulate exactly that and re-read it, the same way any CSV comes in (L06):

tmp <- survey
tmp$rating_txt <- as.character(1:120 %% 5 + 1)   # a made-up 1-5 rating column
tmp$rating_txt[7] <- "5 stars"                    # one contaminated cell
write.csv(tmp, "data/contaminated_sim.csv", row.names = FALSE)
contaminated <- read.csv("data/contaminated_sim.csv")

read.csv() doesn’t know which cell is the “wrong” one — it just sees that the column isn’t consistently numeric, so it imports the entire column as text:

class(contaminated$rating_txt)
[1] "character"
mean(contaminated$rating_txt)
[1] NA
Warning message:
In mean.default(x, ..., na.rm = na.rm) :
  argument is not numeric or logical: returning NA

Cause: mean() needs numbers; a character column — even one that’s mostly digits — is not numeric to R until you explicitly convert it, and one stray non-numeric cell is enough to force the whole column to import as text.

Fix: find the offending cell(s), fix or remove them, then convert:

bad_rows <- contaminated[is.na(suppressWarnings(as.numeric(contaminated$rating_txt))), ]
bad_rows[, c("student_id", "rating_txt")]
  student_id rating_txt
7       S007    5 stars
contaminated$rating_txt[7] <- "5"
contaminated$rating <- as.numeric(contaminated$rating_txt)
mean(contaminated$rating)
[1] 3.016667

107. cannot open the connection / file not found

read.csv("data/servey_sim.csv")
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'data/servey_sim.csv': No such file or directory

Cause: a typo (servey instead of survey) — or, just as often, a correctly spelled file that doesn’t exist relative to your current working directory, the rule L03 sets up and L06 applies to every CSV import.

Fix: list.files() shows you the truth about what’s actually there before you guess again:

list.files("data", pattern = "survey")
[1] "make_survey_sim.R" "survey_sim.csv"   
dim(read.csv("data/survey_sim.csv"))
[1] 120   9

118. there is no package called '...'

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

Cause: a typo in the package name (moasic instead of mosaic) — or a correctly spelled package that genuinely isn’t installed on this machine yet. R can only load a package it can find by that exact name.

Fix: check the spelling first (this guide uses exactly two package names throughout, mosaic and BSDA — see L05); if it’s really missing, install it once with install.packages("mosaic") (L05), then load it:

library(mosaic)

Loads silently — on JupyterHub, mosaic and BSDA are pre-installed (see L05), so install.packages() is almost never needed there; it’s mainly a local-install step.

12A general strategy for any error you haven’t seen yet

  1. Read the error text itself, top to bottom — R almost always names the exact function and often the exact argument that failed.

  2. Check spelling of every variable, column, and package name involved — the single most common cause across all eight errors above.

  3. Check types with class() — most of the errors in this lesson boil down to R having a different type of object than the code assumed.

  4. Check data = — confirm the data frame you passed actually contains every column your formula names.

  5. Restart and re-run top to bottom (L03) if something that worked before mysteriously stops working — a forgotten library() call after a kernel restart (error #2) is the most common reason.

13Summary