简体   繁体   English

R 预测拟合的残差?

[英]R Residuals from predicted fit?

I understand that when you generate a linear model, you can pull the residuals from the fit like this:我知道当您生成线性 model 时,您可以像这样从拟合中提取残差:

# Model
model <- lm(y ~ x, data = coolstuff)

# Residuals
myresids <- model$residuals

I understand further that you can use this model to predict values based on a second data set (eg, a validation data set) like this:我进一步了解您可以使用此 model 来预测基于第二个数据集(例如,验证数据集)的值,如下所示:

mypreds <- predict(model, newdata = coolvalid)

Where I'm lost is where I can find the residuals from the prediction.我迷路的地方就是我可以从预测中找到残差的地方。 predict doesn't generate a data frame or a tibble - just a named list of numbers. predict不会生成数据框或小标题 - 只是一个命名的数字列表。

Where can I find the residuals from the predictions?我在哪里可以找到预测的残差?

Exactly as DanY points out in the comments, the residual is simply the observed value - the predicted value.正如 DanY 在评论中指出的那样,残差只是观察值-预测值。 See below for simple example with built in data.有关内置数据的简单示例,请参见下文。

# sample data
set.seed(1)
split_indicies <- sample(nrow(mtcars), nrow(mtcars)/2)
train <- mtcars[split_indicies,]
test <- mtcars[-split_indicies,]

# model
model <- lm(mpg ~ disp, data = train)

# residuals of prediction are actual - predicted
test$mpg - predict(model, data = test)
#> Pontiac Firebird   Hornet 4 Drive       Duster 360        Mazda RX4 
#>        9.8318659       -0.1503095        3.4749151        1.4901610 
#>    Mazda RX4 Wag      AMC Javelin        Merc 280C      Merc 450SLC 
#>       -0.1098390       -0.5448161       -5.2950183       -7.7129664 
#>         Fiat 128      Honda Civic   Ford Pantera L    Toyota Corona 
#>      -15.8775915      -11.7018628        0.5021011      -11.2626474 
#>         Merc 280       Volvo 142E   Toyota Corolla     Ferrari Dino 
#>        4.7049817        1.4746340        3.8075878       -8.5311955

Created on 2022-02-07 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2022-02-07

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM