线性模型中相互作用项的影响

时间:2018-06-12 11:20:29

标签: r lm

我正在使用effects包来查找线性模型中变量的效果。

library(effects)
data(iris)

lm1 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length*Petal.Width,data=iris)

对于模型中的简单术语,我可以使用

获取每个数据点的效果
effect("Sepal.Width", lm1, xlevels=iris['Sepal.Width'])

如何在每个点为我的交互项获得类似的1维值向量?这甚至有意义吗?我尝试过的所有事情都是返回一个二维矩阵,例如

effect("Petal.Length:Petal.Width", lm1 ,xlevels=iris['Petal.Length']*iris['Petal.Width'])

我不确定本例中xlevels参数应该用什么来给我提供的不仅仅是默认的5个等间距点。

1 个答案:

答案 0 :(得分:0)

想想我已经找到了能给我想要的东西。

# Create dataframe with all possible combinations 
eff_df <- data.frame(effect("Petal.Length:Petal.Width",lm1,xlevels=list(Petal.Length=iris$Petal.Length, Petal.Width=iris$Petal.Width)))

# Create column to merge on in eff_df 
eff_df$merge_col <- paste0(eff_df$Petal.Length,eff_df$Petal.Width)

# Create column it will share in iris
iris$merge_col <- paste0(iris$Petal.Length,iris$Petal.Width)

# Only eff_df$fit values which correspond to a value in iris will be merged 
iris <- merge(iris, eff_df[,c(7,3)], by="merge_col", all.x=T)

然后效果向量存储在iris$fit

相关问题