R中变量的拟合值

Fitted Values by Variable in R

我想按变量查看拟合值,同时仍然考虑模型中的所有其他变量。我会将这些描述为 partial/marginal 拟合值。我在下面有一个玩具示例。此数据集内置于 R 中。这可能吗?

Seatbelts <- data.frame(Seatbelts)
head(Seatbelts)

Seatbelts<-Seatbelts[complete.cases(Seatbelts),]

## 75% of the sample size
smp_size <- floor(0.75 * nrow(Seatbelts))

## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(Seatbelts)), size = smp_size)

train <- Seatbelts[train_ind, ]
test <- Seatbelts[-train_ind, ]

# glm()
m1 <- glm(DriversKilled  ~  front + rear + kms + PetrolPrice + VanKilled + law,
          family=poisson(link = "log"),
          data=train)
fitted(m1)

在这里,您可以在数据框中获得具有 glm 模型拟合值的变量值:

data.frame(front = train$front, rear = train$rear, kms = train$kms, 
           PetrolPrice = train$PetrolPrice, VanKilled = train$VanKilled, 
           law = train$law, Fitted = fitted(m1))

我不确定,但我认为您正在寻找效果图(或相应的数据)。

library(effects)
plot(allEffects(m1))

要获取特定值,您可以使用(例如)as.data.frame(allEffects(m1))(其中 returns 一个 list 数据帧,每个预测变量一个).

emmeans 包具有 similar/overlapping 功能。