1Objectives¶
By the end of this lesson you will be able to:
Recognize the eight R errors and warnings students learning R for statistics hit most often.
Diagnose the cause behind each message, not just the symptom.
Fix each one with a small, concrete change to your code.
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/warning | Usual cause |
|---|---|---|
| 1 | object '...' not found | Typo in a variable/column name, or using a bare column name outside a formula |
| 2 | could not find function "..." | Forgot library(mosaic) (or BSDA) this session |
| 3 | non-numeric argument to binary operator | Doing arithmetic between a numeric column and a text/factor column |
| 4 | object '...' not found (inside a formula) | data = points at the wrong data frame — the column you named lives somewhere else |
| 5 | Invalid formula type | Passed a $-extracted vector where a function wanted a ~ formula |
| 6 | argument is not numeric or logical: returning NA | A numeric-looking column imported as text/character because of one contaminated cell |
| 7 | cannot open the connection / No such file or directory | Typo’d file name, or wrong working directory |
| 8 | there 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 foundCause: 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.787552. 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 063. non-numeric argument to binary operator¶
survey$sleep_hours + survey$petError in survey$sleep_hours + survey$pet :
non-numeric argument to binary operatorCause: + (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 (L05–L07),
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 074. 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 foundCause: 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 085. $ 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 NACause: 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 starscontaminated$rating_txt[7] <- "5"
contaminated$rating <- as.numeric(contaminated$rating_txt)
mean(contaminated$rating)[1] 3.016667107. 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 directoryCause: 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 9118. 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¶
Read the error text itself, top to bottom — R almost always names the exact function and often the exact argument that failed.
Check spelling of every variable, column, and package name involved — the single most common cause across all eight errors above.
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.Check
data =— confirm the data frame you passed actually contains every column your formula names.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¶
All eight errors above are things everyone learning R this way hits, not a sign you’re doing something unusually wrong.
object '...' not foundcan mean a typo’d bare name (#1) or a formula whosedata =doesn’t hold that column (#4) — same message, different fix, so read the code, not just the text.could not find function(#2) andthere is no package called(#8) both trace back tolibrary()— a session that never ran it, or a package name that’s misspelled or genuinely not installed.non-numeric argument(#3) and themean()warning in #6 both come from R’s type system: arithmetic needs numbers, and one contaminated cell in a CSV column is enough to makeread.csv()import the whole column as text —class()catches both immediately.$pulls a plain vector out of a data frame;gf_*(and every othermosaicfunction) wants a~formula plusdata =instead (#5) — they are not interchangeable even though both are valid R.list.files()(#7) turns a guess about a file path into a fact.The full script that reproduces every error and every fix on this page — by actually running the broken code — is committed at
data/make_L14_examples.R; run it yourself and you’ll see the exact same messages.