當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R hardhat model_offset 提取模型偏移

model_offset() 從模型框架中提取數字偏移量。它受到 stats::model.offset() 的啟發,但具有更好的錯誤消息並且稍微嚴格一些。

用法

model_offset(terms, data)

參數

terms

data 對應的 "terms" 對象,從對 model_frame() 的調用返回。

data

從調用 model_frame() 返回的數據幀。

表示偏移量的數值向量。

細節

如果標記為偏移量的列不是數字,則會拋出一條不錯的錯誤消息,準確告訴您哪一列有問題。

stats::model.offset() 還允許將名為 "(offset)" 的列與 stats::offset() 標記的任何其他列一起視為偏移量。但是,stats::model.matrix() 不會將這些列識別為偏移量(因此它不會按應有的方式刪除它們)。由於這種不一致,model_offset() 不會對名為 "(offset)" 的列進行特殊處理。

例子


x <- model.frame(Species ~ offset(Sepal.Width), iris)

model_offset(terms(x), x)
#>   [1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 3.7 3.4 3.0 3.0 4.0 4.4 3.9
#>  [18] 3.5 3.8 3.8 3.4 3.7 3.6 3.3 3.4 3.0 3.4 3.5 3.4 3.2 3.1 3.4 4.1 4.2
#>  [35] 3.1 3.2 3.5 3.6 3.0 3.4 3.5 2.3 3.2 3.5 3.8 3.0 3.8 3.2 3.7 3.3 3.2
#>  [52] 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 2.7 2.0 3.0 2.2 2.9 2.9 3.1 3.0 2.7
#>  [69] 2.2 2.5 3.2 2.8 2.5 2.8 2.9 3.0 2.8 3.0 2.9 2.6 2.4 2.4 2.7 2.7 3.0
#>  [86] 3.4 3.1 2.3 3.0 2.5 2.6 3.0 2.6 2.3 2.7 3.0 2.9 2.9 2.5 2.8 3.3 2.7
#> [103] 3.0 2.9 3.0 3.0 2.5 2.9 2.5 3.6 3.2 2.7 3.0 2.5 2.8 3.2 3.0 3.8 2.6
#> [120] 2.2 3.2 2.8 2.8 2.7 3.3 3.2 2.8 3.0 2.8 3.0 2.8 3.8 2.8 2.8 2.6 3.0
#> [137] 3.4 3.1 3.0 3.1 3.1 3.1 2.7 3.2 3.3 3.0 2.5 3.0 3.4 3.0

xx <- model.frame(Species ~ offset(Sepal.Width) + offset(Sepal.Length), iris)

model_offset(terms(xx), xx)
#>   [1]  8.6  7.9  7.9  7.7  8.6  9.3  8.0  8.4  7.3  8.0  9.1  8.2  7.8
#>  [14]  7.3  9.8 10.1  9.3  8.6  9.5  8.9  8.8  8.8  8.2  8.4  8.2  8.0
#>  [27]  8.4  8.7  8.6  7.9  7.9  8.8  9.3  9.7  8.0  8.2  9.0  8.5  7.4
#>  [40]  8.5  8.5  6.8  7.6  8.5  8.9  7.8  8.9  7.8  9.0  8.3 10.2  9.6
#>  [53] 10.0  7.8  9.3  8.5  9.6  7.3  9.5  7.9  7.0  8.9  8.2  9.0  8.5
#>  [66]  9.8  8.6  8.5  8.4  8.1  9.1  8.9  8.8  8.9  9.3  9.6  9.6  9.7
#>  [79]  8.9  8.3  7.9  7.9  8.5  8.7  8.4  9.4  9.8  8.6  8.6  8.0  8.1
#>  [92]  9.1  8.4  7.3  8.3  8.7  8.6  9.1  7.6  8.5  9.6  8.5 10.1  9.2
#> [105]  9.5 10.6  7.4 10.2  9.2 10.8  9.7  9.1  9.8  8.2  8.6  9.6  9.5
#> [118] 11.5 10.3  8.2 10.1  8.4 10.5  9.0 10.0 10.4  9.0  9.1  9.2 10.2
#> [131] 10.2 11.7  9.2  9.1  8.7 10.7  9.7  9.5  9.0 10.0  9.8 10.0  8.5
#> [144] 10.0 10.0  9.7  8.8  9.5  9.6  8.9

# Problematic columns are caught with intuitive errors
tryCatch(
  expr = {
    x <- model.frame(~ offset(Species), iris)
    model_offset(terms(x), x)
  },
  error = function(e) {
    print(e$message)
  }
)
#> Column, 'offset(Species)', is tagged as an offset, but is not numeric. All offsets must be numeric.
源代碼:R/model-offset.R

相關用法


注:本文由純淨天空篩選整理自Davis Vaughan等大神的英文原創作品 Extract a model offset。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。