RMarkdown中ols_vif_tol函数报错:str2lang零长度变量名问题
解决ols_vif_tol函数报错:Error in str2lang(x) : attempt to use zero-length variable name
针对你遇到的这个报错,结合你的代码和已排查的情况,给出几个可行的解决方向:
检查数据列名的合法性
虽然你的模型只用到了success和AREA,但数据中可能存在隐藏的无效列名(比如包含空格、不可见特殊字符),导致ols_vif_tol解析变量名时出错。先查看并清理列名:# 查看所有列名 print(names(pollen)) # 清理列名,移除非字母数字下划线的字符 names(pollen) <- gsub("[^a-zA-Z0-9_]", "", names(pollen)) # 重新拟合模型 model.a <- lm(success ~ AREA, data = pollen) # 再次调用函数 ols_vif_tol(model.a)回退olsrr包到可用版本
新版本的olsrr可能存在兼容性bug,你之前能用说明旧版本是正常的。可以安装指定旧版本:# 先安装devtools(如果没装过) install.packages("devtools") # 安装之前可用的版本,比如0.5.3(可根据你之前的使用情况调整) devtools::install_version("olsrr", version = "0.5.3")安装完成后重启R,再运行代码。
应急手动计算(适配单变量模型)
因为你的模型是单自变量的线性回归,VIF的理论值就是1,Tolerance是1/VIF=1。如果作业允许临时替代,可以先手动输出结果,同时继续排查函数问题:r_sq <- summary(model.a)$r.squared vif_val <- 1 / (1 - r_sq) cat("VIF:", vif_val, "\nTolerance:", 1/vif_val)检查RMarkdown代码块设置
确认代码块的开头是```r,没有额外的错误参数,避免RMarkdown解析代码时出现异常。
你的原始代码:
# Read in data, and check data set #Read in data & set WD: # I'm going to read in my .csv file and rename it so it's shorter setwd("D:/Users/samik/Documents/R_NEW/Data_Analysis_WD/Assignment_3") pollen <- read.csv("D:/Users/samik/Documents/R_NEW/Data_Analysis_WD/Assignment_3/pollinators(5).csv") #The following code is based off the module 2 assignment #Missing values which(is.na(pollen)==TRUE, arr.ind = TRUE) #No missing values! We can move on #Outliers (did badly using boxplots last module so let's try cook's distance method instead) #Need a linear model to do it model.a = lm(success ~ AREA, data = pollen) #The cooks.distance() function cooks <- cooks.distance(model.a) #If it's >4x the mean, it's influential inf.val <- which(cooks >= 4*mean(cooks)) pollen[inf.val,] #Need to plot cook's distance now - This is taken out of Dr. Beatty's mini-lecture plot(cooks, pch="*", cex=2, main="Influential Values by Cook's distance") + abline(h = 4*mean(cooks, na.rm=T), col="red") + text(x=1:length(cooks)+1, y=cooks, labels=ifelse(cooks>4*mean(cooks, na.rm=T),names(cooks),""), col="red") #autocorrelation #We are going to check for correlation and then use a package to check for VIF and tolerance at the same time. We're only looking at AREA and success here. cor(pollen) #Check the VIF and tolerance using the lm we already made library(olsrr) model.a = lm(success ~ AREA, data = pollen) ols_vif_tol(model.a) #Homoscedasticity (good) #Normality (good) # Calculate median success # Plot relationship to see if a linear model might be appropriate
内容的提问来源于stack exchange,提问作者S Fitzgerald
相关产品推荐
相关产品推荐

