我正在尝试编写一个函数,该函数采用可选的权重参数并将其传递给
model.frame
:
test <- function(ff, weights, data) {
mm <- model.frame(ff, data, weights=weights)
y <- model.response(mm)
x <- mm[, 2]
w <- mm[, 3:ncol(mm)-1]
wt <- model.weights(mm)
mat <- cbind(y, x, w, wt)
return(sum(mat))
}
我收到一条错误消息
> test(ff, weight=wt, data=dtaw)
Error in model.frame.default(ff, data, weights = weights) :
invalid type (closure) for variable '(weights)'
Called from: model.frame.default(ff, data, weights = weights)
这是如何重现它
dtaw <- data.frame(y = runif(100))
dtaw$x <- runif(100)
dtaw$w1 <- runif(100)
dtaw$w2 <- runif(100)
dtaw$wt <- runif(100)
ff <- y ~ x + w1 + w2
test(ff, weight=wt, data=dtaw)
另外,有没有更好的方法从函数
model.frame
中的mm
test
中提取第一个rhs变量和其余rhs变量?
这是更新的功能:
test <- function(ff, wt, data) {
mm <- model.frame(ff, data, weights = wt)
y <- model.response(mm)
# Extract RHS variables
rhs_vars <- all.vars(ff[[3]])
x_var <- rhs_vars[1]
w_vars <- rhs_vars[-1]
x <- mm[[x_var]]
w <- mm[w_vars]
wt <- model.weights(mm)
# Combine variables into a matrix
mat <- cbind(y, x, w, wt)
return(sum(mat))
}