我正在定义一个函数来获取回归模型的预测值,其中包含不同亚组(亚群)的调查数据。我使用调查包中的 svyglm 函数。
我的问题涉及处理 svyglm 函数中的子集选项。由于它使用非标准评估,我理解这意味着它不会将列名作为字符串。我尝试只使用不带字符串的列名并引用(enquo)并取消引用它(!!)。但是,这两个选项都不起作用。我也玩过 ensym() 和 expr() 但没有得到任何结果。
资料库
library(dplyr)
library(survey)
library(srvyr)
library(purrr)
library(rlang)
mtcars <- read.table("https://forge.scilab.org/index.php/p/rdataset/source/file/master/csv/datasets/mtcars.csv",
sep=",", header=TRUE)
mtcars_cplx <- mtcars %>% as_survey_design(id = cyl, weights = qsec)
carb <- c(1:8)
cyl <- c(4:8)
new_data <- expand.grid(carb, cyl)
colnames(new_data) <- c("carb", "cyl")
有礼貌
功能和输入
subpop_pred <- function(formula, data, subpop, new_data) {
subpop_quo <- enquo(subpop)
subpop_txt <- data$variables %>% select(!!subpop_quo) %>% colnames()
for(i in min(data$variables[subpop_txt]):max(data$variables[subpop_txt])){
reg <- svyglm(formula, data, subset=!!subpop_quo==i)
pred <- predict(reg, newdata=new_data)
if(exists("reg_end")==TRUE){
pred <- cbind(new_data, pred, confint(pred))
pred[subpop_txt] <- i
reg_end <- rbind(reg_end, pred)
} else {
reg_end <- cbind(new_data, pred, confint(pred))
reg_end[subpop_txt] <- i
}
}
}
subpop_pred(mpg ~ carb + cyl + carb*cyl,
data=mtcars_cplx,
new_data=new_data,
subpop=gear)
输出/错误
Error: Base operators are not defined for quosures.
Do you need to unquote the quosure?
# Bad:
myquosure == rhs
# Good:
!!myquosure == rhs
Call `rlang::last_error()` to see a backtrace
8. stop(cnd)
7. abort(paste_line("Base operators are not defined for quosures.",
"Do you need to unquote the quosure?", "", " # Bad:", bad,
"", " # Good:", good, ))
6. Ops.quosure(subpop_quo, i)
5. eval(subset, model.frame(design), parent.frame())
4. eval(subset, model.frame(design), parent.frame())
3. svyglm.survey.design(formula, data, subset = !!subpop_quo ==
i)
2. svyglm(formula, data, subset = !!subpop_quo == i)
1. subpop_pred(mpg ~ carb + cyl + carb * cyl, data = mtcars_cplx,
new_data = new_data, subpop = gear)
没有定论
功能和输入
subpop_pred <- function(formula, data, subpop, new_data) {
subpop_quo <- enquo(subpop)
subpop_txt <- data$variables %>% select(!!subpop_quo) %>% colnames()
for(i in min(data$variables[subpop_txt]):max(data$variables[subpop_txt])){
reg <- svyglm(formula, data, subset=subpop==i)
pred <- predict(reg, newdata=new_data)
if(exists("reg_end")==TRUE){
pred <- cbind(new_data, pred, confint(pred))
pred[subpop_txt] <- i
reg_end <- rbind(reg_end, pred)
} else {
reg_end <- cbind(new_data, pred, confint(pred))
reg_end[subpop_txt] <- i
}
}
}
subpop_pred(mpg ~ carb + cyl + carb*cyl, data=mtcars_cplx, new_data=new_data, subpop=gear)
输出
Error in eval(subset, model.frame(design), parent.frame()) :
object 'gear' not found
5. eval(subset, model.frame(design), parent.frame())
4. eval(subset, model.frame(design), parent.frame())
3. svyglm.survey.design(formula, data, subset = subpop == i)
2. svyglm(formula, data, subset = subpop == i)
1. subpop_pred(mpg ~ carb + cyl + carb * cyl, data = mtcars_cplx,
new_data = new_data, subpop = gear)
您知道如何使该功能正常工作吗?