將殘差添加到 DataFrame
用法
add_residuals(data, model, var = "resid")
spread_residuals(data, ...)
gather_residuals(data, ..., .resid = "resid", .model = "model")
參數
- data
-
用於生成殘差的 DataFrame
- model, var
-
add_residuals
采用單個model
;輸出列將被稱為resid
- ...
-
gather_residuals
和spread_residuals
采用多個模型。該名稱將從參數名稱或模型名稱中獲取。 - .resid, .model
-
gather_residuals
使用的變量名稱。
值
一個 DataFrame 。 add_residuals
將一個新列 .resid
添加到輸入 data
中。 spread_residuals
為每個模型添加一列。 gather_predictions
添加兩列 .model
和 .resid
,並為每個模型重複輸入行。
例子
df <- tibble::tibble(
x = sort(runif(100)),
y = 5 * x + 0.5 * x ^ 2 + 3 + rnorm(length(x))
)
plot(df)
m1 <- lm(y ~ x, data = df)
df %>% add_residuals(m1)
#> # A tibble: 100 × 3
#> x y resid
#> <dbl> <dbl> <dbl>
#> 1 0.0130 2.05 -0.636
#> 2 0.0248 4.16 1.40
#> 3 0.0256 3.72 0.961
#> 4 0.0267 1.98 -0.788
#> 5 0.0312 3.60 0.804
#> 6 0.0356 4.77 1.95
#> 7 0.0383 2.25 -0.580
#> 8 0.0397 1.16 -1.68
#> 9 0.0573 2.34 -0.607
#> 10 0.0672 1.99 -1.02
#> # … with 90 more rows
m2 <- lm(y ~ poly(x, 2), data = df)
df %>% spread_residuals(m1, m2)
#> # A tibble: 100 × 4
#> x y m1 m2
#> <dbl> <dbl> <dbl> <dbl>
#> 1 0.0130 2.05 -0.636 -0.816
#> 2 0.0248 4.16 1.40 1.24
#> 3 0.0256 3.72 0.961 0.796
#> 4 0.0267 1.98 -0.788 -0.951
#> 5 0.0312 3.60 0.804 0.646
#> 6 0.0356 4.77 1.95 1.80
#> 7 0.0383 2.25 -0.580 -0.729
#> 8 0.0397 1.16 -1.68 -1.83
#> 9 0.0573 2.34 -0.607 -0.733
#> 10 0.0672 1.99 -1.02 -1.14
#> # … with 90 more rows
df %>% gather_residuals(m1, m2)
#> # A tibble: 200 × 4
#> model x y resid
#> <chr> <dbl> <dbl> <dbl>
#> 1 m1 0.0130 2.05 -0.636
#> 2 m1 0.0248 4.16 1.40
#> 3 m1 0.0256 3.72 0.961
#> 4 m1 0.0267 1.98 -0.788
#> 5 m1 0.0312 3.60 0.804
#> 6 m1 0.0356 4.77 1.95
#> 7 m1 0.0383 2.25 -0.580
#> 8 m1 0.0397 1.16 -1.68
#> 9 m1 0.0573 2.34 -0.607
#> 10 m1 0.0672 1.99 -1.02
#> # … with 190 more rows
相關用法
- R modelr add_predictions 將預測添加到 DataFrame
- R modelr add_predictors 將預測變量添加到公式中
- R modelr typical 求典型值
- R modelr resample “惰性”重采樣。
- R modelr crossv_mc 生成測試訓練對以進行交叉驗證
- R modelr model_matrix 構建設計矩陣
- R modelr model-quality 計算給定數據集的模型質量
- R modelr permute 生成 n 個排列重複。
- R modelr fit_with 擬合公式列表
- R modelr data_grid 生成數據網格。
- R modelr formulas 創建公式列表
- R modelr seq_range 生成向量範圍內的序列
- R modelr resample_partition 生成數據幀的獨占分區
- R modelr na.warn 處理缺失值並發出警告
- R modelr bootstrap 生成 n 個引導程序重複。
- R modelr resample_bootstrap 生成 boostrap 複製
- R vcov.gam 從 GAM 擬合中提取參數(估計器)協方差矩陣
- R gam.check 擬合 gam 模型的一些診斷
- R matrix轉list用法及代碼示例
- R as 強製對象屬於某個類
- R null.space.dimension TPRS 未懲罰函數空間的基礎
- R language-class 表示未評估語言對象的類
- R gam.reparam 尋找平方根懲罰的穩定正交重新參數化。
- R className 類名包含對應的包
- R extract.lme.cov 從 lme 對象中提取數據協方差矩陣
注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Add residuals to a data frame。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。