查找交互术语的效果

时间:2018-05-22 17:11:02

标签: r lm

我试图在线性模型中看到不同变量的影响。下面是一个简单线性模型的示例,以及我如何检查每个变量的效果:

library(MASS)
library(effects)
library(qdapTools)    

iris <- iris

trainiris <- iris[1:100,]
lm_iris <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data=trainiris)
model_variables = c("Sepal.Width","Petal.Length","Petal.Width")

testiris <- iris[101:150,]

# Block of code below adds new columns to testiris showing the effects of each variable in the model
eff_names <- vector(length=length(model_variables))
for(i in 1:length(model_variables)){
  varname = model_variables[i] # Set variable name
  newcol = paste0("eff_",varname) # Name new column
  eff_names[[i]] <- newcol
  varvalues = unlist(testiris[model_variables[i]]) # unlist
  eff1 = eval(parse(text = paste0('Effect(mod = lm_iris,focal.predictors = varname, xlevels = list("',varname,'"=varvalues))')));eff1 # Calculate the effects
  eff2 = data.frame(round(eff1$fit,4), eff1$x);eff2
  eff2 = unique(eff2)
  colnames(eff2) = c("fit","var");eff2 # for the lookup
  effects = round(lookup(varvalues,eff2$var,eff2$fit),2)
  testiris[newcol] <- NA # Creates the new column filled with "NA"
  eval(parse(text = paste0("testiris$", newcol, "<- effects")));paste0("testiris$", newcol, "<- effects") # appends effects to new columns
}

这为每个变量的testiris添加了一个新列。

现在说我要添加交互术语,因此模型变为

lm_iris <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Petal.Length*Petal.Width, data=trainiris)
model_variables = c("Sepal.Width","Petal.Length","Petal.Width","Petal.Length*Petal.Width")

当我运行相同的代码块来生成效果时,会出错。如何检查交互项的影响?

Error in `[.data.frame`(testiris, model_variables[i]) : 
  undefined columns selected

0 个答案:

没有答案