GLM模型拟合报错‘NA/NaN/Inf in 'y'’排查求助
Hey there, let's work through this GLM error you're facing. Even though you confirmed there are no NA values in your dataset, the "NA/NaN/Inf in 'y'" error can pop up from a few hidden issues—let's break them down one by one:
Check for Inf/NaN in your response variable
Thetable(is.na())check only catches NA values, not infinite (Inf) or not-a-number (NaN) values. Your response variablerope.directional.changemight have these hidden issues. Run these quick checks to confirm:# Check for infinite values in the response any(is.infinite(rope_complete$rope.directional.change)) # Check for NaN values in the response any(is.nan(rope_complete$rope.directional.change))If either returns
TRUE, you'll need to clean those values (e.g., filter out rows with Inf/NaN or correct the source data).Investigate your offset term
Your offset useslog(rope_complete$rope.Time.of.the.shark.in.the.video)—and here's a common gotcha: if any value inrope.Time.of.the.shark.in.the.videois 0,log(0)returns-Inf, which will throw off the model. Check for zero values with:any(rope_complete$rope.Time.of.the.shark.in.the.video == 0)If you find zeros, you have a few fixes:
- Filter out rows where the time is 0 (if those observations aren't meaningful for your analysis)
- Add a tiny constant to the time values before taking the log (e.g.,
log(rope.Time.of.the.shark.in.the.video + 0.01)to avoidlog(0))
Verify your code is complete and clean
The code snippet you shared cuts off mid-offset definition:offset( log(rope_complete$rope.Tim.... Make sure you've written the full offset term (it should referencerope.Time.of.the.shark.in.the.videoproperly). Also, using thedataparameter will make your code cleaner and less prone to typos:# Corrected, cleaner code example (with offset adjustment if needed) directional_turn_fit <- glm(rope.directional.change ~ rope.X...Sound + offset(log(rope.Time.of.the.shark.in.the.video + 0.01)), data = rope_complete)Double-check variable types
Ensurerope.directional.changeis a numeric variable (not a factor or character string). A wrong variable type can sometimes trigger unexpected errors. Confirm with:class(rope_complete$rope.directional.change)
Start with checking the offset term first—odds are that zero time values are causing the Inf values that break your model.
内容的提问来源于stack exchange,提问作者Jessi

