英文:
Dynamically create and use new variable/parameter names and values in R
问题
以下是您要翻译的部分:
对于以下函数,我想使提供给 datagrid()
和 'by' 的变量(名称和值)是动态的,从数据框中提取并在每次 for 循环迭代时更新。对于如何实现这一点,任何建议都将不胜感激!
marginaleffects::avg_predictions(mice::as.mira(fits),
newdata=datagrid(HOMEETA1_Infancy=c(-0.87125,0.48375),
HOMEETA1_Toddlerhood=c(-0.403875,1.123375),
HOMEETA1_Childhood=c(-0.02475,1.60475)),
by=c("HOMEETA1_Infancy","HOMEETA1_Toddlerhood","HOMEETA1_Childhood"))
Datagrid 需要 'named arguments',但我还没有找出如何使它们动态化(通过列表、数据框等)。
英文:
For the following functions, I would like to make the variables (names and values) provided to datagrid() and 'by' dynamic, pulling from a dataframe and updating with each iteration of a for loop. Any ideas for how to implement this would be much appreciated!
marginaleffects::avg_predictions(mice::as.mira(fits),
newdata=datagrid(HOMEETA1_Infancy=c(-0.87125,0.48375),
HOMEETA1_Toddlerhood=c(-0.403875,1.123375),
HOMEETA1_Childhood=c(-0.02475,1.60475)),
by=c("HOMEETA1_Infancy","HOMEETA1_Toddlerhood","HOMEETA1_Childhood"))
Datagrid requires 'named arguments' and I have not figured out how to make those dynamic (via a list, dataframe, etc.).
答案1
得分: 1
Sure, here are the translated parts:
如果我们有一个命名列表或数据框,我们可以使用 datagrid
与 do.call
do.call(datagrid, yourdf)
一个可重现的示例
mod <- lm(mpg ~ wt + drat, data = mtcars)
> datagrid(model = mod, wt = 1:2, drat = 3:4)
mpg wt drat
1 20.09062 1 3
2 20.09062 1 4
3 20.09062 2 3
4 20.09062 2 4
> lst1 <- list(wt = 1:2, drat = 3:4)
> do.call(datagrid, c(list(model = mod), lst1))
mpg wt drat
1 20.09062 1 3
2 20.09062 1 4
3 20.09062 2 3
4 20.09062 2 4
英文:
If we have a named list or a data.frame, we can use datagrid
with do.call
do.call(datagrid, yourdf)
A reproducible example
mod <- lm(mpg ~ wt + drat, data = mtcars)
> datagrid(model = mod, wt = 1:2, drat = 3:4)
mpg wt drat
1 20.09062 1 3
2 20.09062 1 4
3 20.09062 2 3
4 20.09062 2 4
> lst1 <- list(wt = 1:2, drat = 3:4)
> do.call(datagrid, c(list(model = mod), lst1))
mpg wt drat
1 20.09062 1 3
2 20.09062 1 4
3 20.09062 2 3
4 20.09062 2 4
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论