gpt4 book ai didi

r - 如何在R函数中将参数作为列表传递

转载 作者:行者123 更新时间:2023-12-02 11:22:24 25 4
gpt4 key购买 nike

我有很多参数的函数。因此,我想创建一个参数列表并将其传递给函数。
?mean函数为例:

mean(x, trim = 0, na.rm = FALSE, ...)
因此,可以说我想计算分配给变量 1:10x的平均值,但将其他参数作为列表传递:
gm <- list (trim = 0, na.rm = FALSE)

mean(1:10, gm)
#R> Error in mean.default(1:10, gm) : 'trim' must be numeric of length one
我尝试使用 do.call,但也不起作用。
do.call(mean,list(1:10, gm))
#R> Error in mean.default(1:10, list(trim = 0, na.rm = FALSE)) :
#R> 'trim' must be numeric of length one

最佳答案

如评论中所述,您的gm do.call 形状错误,它将您的选项列表解释为trim参数。

要使参数正确成形,请使用 c :

gm <- list(trim=0, na.rm=FALSE)
do.call(mean, c(list(1:10), gm))
[1] 5.5

关于r - 如何在R函数中将参数作为列表传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com