K.J. Mhango | HARUG © 2025
lm
, aov
, lmer
, lme
traceback
, browser
, rlang
)(Blog source at the end)
mean(c(1, 7, 13 # ← missing ')'
Error: unexpected end of input
mean(c(1, 7, 13)) # ✓ fixed
ggplot(mtcars) # not yet loaded
Error in ggplot(mtcars) : could not find function "ggplot"
install.packages("ggplot2"); library(ggplot2)
ggplot(mtcars) + geom_point(aes(mpg, wt))
sumary(cars) # oops
Error in sumary(cars) : could not find function "sumary"
summary(cars) # ✓
seq(1, 10, lngth = 2)
Error in seq.default(1, 10, lngth = 2) :
unused argument (lngth = 2)
seq(1, 10, length = 2) # ✓
x <- factor(1:3)
mean(x)
Warning in mean.default(x) : argument is not numeric or logical: returning NA
[1] NA
mean(as.numeric(as.character(x))) # ✓
+
in ggplot2ggplot(mtcars, aes(mpg, wt))
geom_point()
Error: object 'geom_point' not found
ggplot(mtcars, aes(mpg, wt)) +
geom_point()
=
with ==
if(x = 5) "hi"
Error: unexpected '=' in "if(x ="
if(x == 5) "hi" # ✓
mtcars[, "mpgX"]
Error in `[.data.frame`(mtcars, , "mpgX") :
undefined columns selected
mtcars[, "mpg"] # ✓
read.csv("data/myfile.csv")
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'data/myfile.csv': No such file or directory
read.csv(file.choose()) # ✓
$
on atomic vectorsv <- 1:10
v$foo
Error in v$foo : $ operator is invalid for atomic vectors
list(foo = v)$foo # ✓
X′X
is singular (rank < p) → cannot invert → no unique β̂.lm()
cleverly drops redundant columns, but still in left to right order.lm
, aov
, lmer
, lme
Simulated examples & fixes
lm()
Error 1 – Singular FitMessage: “coefficients not defined because of singularities”
df <- data.frame(
y = rnorm(10),
x1 = 1:10,
x2 = 51:60, # collinear with x1
x3=31:40
)
lm(y ~ x1 + x2+x3, data = df)
Fix: drop redundant predictor
lm(y ~ x1, data = df)
lm()
Lengths DifferMessage: “variable lengths differ”
x <- 1:10
y <- rnorm(9)
lm(y ~ x) # unequal lengths
Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) :
variable lengths differ (found for 'x')
Fix: align vector lengths.
aov()
Grouping Factor Has One Leveldf <- subset(PlantGrowth, group == "ctrl")
aov(weight ~ group, data = df) # fails
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels
Fix: ensure ≥ 2 levels.
lmer()
Error 1 – One-Level Random EffectMessage: “number of levels of a grouping factor is 1”
library(lme4)
df <- data.frame(
y = rnorm(10),
x = rnorm(10),
group = rep("A", 10)
)
lmer(y ~ x + (1 | group), data = df)
Error: grouping factors must have > 1 sampled level
Fix: add more group levels.
lmer()
Error 2 – Convergence / NaNsdf <- sleepstudy
df$Days <- df$Days * 1000 # poor scaling
lmer(Reaction ~ Days + (Days | Subject), data = df)
In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv, :
Model failed to converge with max|grad| = 3.50551 (tol = 0.002, component 1)
In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv, :
Model is nearly unidentifiable: very large eigenvalue
- Rescale variables?;Model is nearly unidentifiable: large eigenvalue ratio
Fix:
scale/center predictors
check correlation between random intercept and random slope
set.seed(1)
d <- data.frame(
y = rnorm(40),
x1 = rnorm(40)
)
d$x2 <- d$x1 # duplicate
lm(y ~ x1 + x2, d) # x2 dropped (NA coef)
iris$Species <- factor(iris$Species)
X.bad <- cbind(1, model.matrix(~ Species + 0, iris)) # intercept + all dummies
qr(X.bad)$rank # 3 < 4 ⇒ singular
Fix by dropping one level (~ Species
) or omitting intercept (~ Species + 0
).
data(longley)
m <- lm(Employed ~ ., longley)
kappa(m) # ≫ 10^4 : ill-conditioned
High condition # → unstable estimates.
(1e16 + 1) - 1e16 # 0
sqrt(2)^2 - 2 # 4.4e-16
n <- 5
df <- as.data.frame(matrix(rnorm(n*7), n))
names(df) <- c("y", paste0("x",1:6))
lm(y ~ ., df) # several NA betas (rank ≤ n)
Need ≥ observations than parameters.
traceback()
f <- function(x) {
m<-x
g(x)
}
g <- function(x) {
mm=x
m2=mm
x + 1}
f("a") # error
traceback() # g → f
traceback()
2: g(x) at #3
1: f("a")
browser()
/ debug()
calc <- function(a,b){
browser() # pause here
a/b
}
calc(1,0)
rlang
library(dplyr)
mtcars %>% mutate(z = log(mpgX)) # typo
rlang::last_error()
rlang::last_trace()
X′X
underpins OLS – watch rank!?lm
, ?lmer
, ?lme
docs & vignettesQuestions?