在函数中使用“marg” - 如何正确引用?
Posted
技术标签:
【中文标题】在函数中使用“marg” - 如何正确引用?【英文标题】:Using "marg" in a function - how to enquote correctly? 【发布时间】:2022-01-03 22:43:01 【问题描述】:想象一下我有一个类似的回归:
regression <- glm(mpg ~ am * hp, data = mtcars)
我可以使用 modmarg
包轻松计算边际效应:
library(modmarg)
margins <- marg(
regression, var_interest = "am",
at = list("hp" = 52:110),
type = "effects")
但是,我有许多具有不同变量的模型来计算边距,所以我想将其放入一个函数中:
plotting_marg <- function(reg, cov)
margins <- marg(
reg, var_interest = "truth",
at = list(cov = 52:110),
type = "effects")
plotting_marg(regression, "hp", -3, 3)
Error in .marg(mod = mod, var_interest = var_interest, data = data, weights = weights, :
var_interest %in% names(data) is not TRUE
这不起作用,大概是因为 cov
没有正确引用。我玩过enquo
,但没有运气。怎么走?
【问题讨论】:
【参考方案1】:使用传递的对象命名list
可以使用setNames
完成
plotting_marg <- function(reg, cov)
marg(
reg, var_interest = "am",
at = setNames(list(52:110), cov),
type = "effects")
-测试
> plotting_marg(regression, "hp")
$`hp = 52`
Label Margin Standard.Error Test.Stat P.Value Lower CI (95%) Upper CI (95%)
1 am = 0 0.000000 0.000000 NaN NaN 0.000000 0.000000
2 am = 1 5.238604 1.918006 2.731276 0.01079466 1.309746 9.167462
$`hp = 53`
Label Margin Standard.Error Test.Stat P.Value Lower CI (95%) Upper CI (95%)
1 am = 0 0.000000 0.000000 NaN NaN 0.000000 0.000000
2 am = 1 5.239007 1.904537 2.750803 0.01030278 1.337739 9.140274
$`hp = 54`
Label Margin Standard.Error Test.Stat P.Value Lower CI (95%) Upper CI (95%)
1 am = 0 0.000000 0.000000 NaN NaN 0.000000 0.000000
2 am = 1 5.239409 1.891116 2.770539 0.009827057 1.365635 9.113184
...
或者可能需要来自dplyr/purrr
的lst
plotting_marg <- function(reg, cov)
marg(
reg, var_interest = "am",
at = dplyr::lst(!!cov := 52:110),
type = "effects")
-测试
> plotting_marg(regression, "hp")
$`hp = 52`
Label Margin Standard.Error Test.Stat P.Value Lower CI (95%) Upper CI (95%)
1 am = 0 0.000000 0.000000 NaN NaN 0.000000 0.000000
2 am = 1 5.238604 1.918006 2.731276 0.01079466 1.309746 9.167462
$`hp = 53`
Label Margin Standard.Error Test.Stat P.Value Lower CI (95%) Upper CI (95%)
1 am = 0 0.000000 0.000000 NaN NaN 0.000000 0.000000
2 am = 1 5.239007 1.904537 2.750803 0.01030278 1.337739 9.140274
$`hp = 54`
Label Margin Standard.Error Test.Stat P.Value Lower CI (95%) Upper CI (95%)
1 am = 0 0.000000 0.000000 NaN NaN 0.000000 0.000000
2 am = 1 5.239409 1.891116 2.770539 0.009827057 1.365635 9.113184
...
【讨论】:
像魅力一样工作以上是关于在函数中使用“marg” - 如何正确引用?的主要内容,如果未能解决你的问题,请参考以下文章