我正在使用
nlme
包来创建广义最小二乘模型。这是一个带有生成数据集的可重现示例:
# Load necessary library
library(nlme)
# Generate some data
set.seed(123)
my_data <- data.frame(
y = rnorm(100),
x = runif(100),
z = factor(rep(1:2, each = 50)),
g = factor(rep(1:2, each = 50)),
h = factor(rep(1:2, 50))
)
# Create the model
mdl <- gls(y ~ x * z,
weights = varIdent(form = ~ 1 | g * h),
data = my_data)
# I can retrieve the model formula like this
model_formula <- formula(mdl)
在这段代码中,我可以使用
formula(mdl)
来获取模型公式。但是,我找不到从 weights
对象检索 mdl
参数的方法。我该怎么做?
它们存储为
attr
ibute。
attr(mdl$modelStruct$varStruct, 'weights')
# 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2
# 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094
# 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2
# 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094
# ...
str(mdl)
在这种情况下有很大帮助。
其实,我们可以给
"gls"
一个新的方法。
weights.gls <- function (object, ...) {
wts <- attr(object$modelStruct$varStruct, 'weights')
if (is.null(wts))
wts
else napredict(object$na.action, wts)
}
weights(mdl)
# 1*1 1*2 1*1 1*2 1*1 1*2 ...
# 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 ...
# ...
nlme::varWeights()
功能:
返回对象表示的方差函数结构对应的标准差的倒数。
varWeights(mdl$modelStruct)
# 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2
# 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094
# 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2 1*1 1*2
# 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094 1.0000000 0.8064094
# etc