Нахождение эффекта члена взаимодействия - PullRequest
0 голосов
/ 22 мая 2018

Я пытаюсь увидеть влияние различных переменных в линейной модели.Ниже приведен пример простой линейной модели и того, как я проверяю эффекты для каждой переменной:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...