在R中动态创建和使用新的变量/参数名称和数值。

huangapple go评论57阅读模式
英文:

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:

如果我们有一个命名列表或数据框,我们可以使用 datagriddo.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 &lt;- lm(mpg ~ wt + drat, data = mtcars)
&gt; 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

&gt; lst1 &lt;- list(wt = 1:2, drat = 3:4)
&gt; 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>



huangapple
  • 本文由 发表于 2023年4月6日 23:52:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定