【问题标题】:R - Pass element of list as argument to function callR - 将列表元素作为参数传递给函数调用
【发布时间】:2017-04-09 21:09:27
【问题描述】:

让我们从一些简单的代码开始:

require(randomForest)
randomForest(mpg~.,mtcars,ntree=10)

这会构建一个由 10 棵树组成的随机森林。

我想要的是将参数存储在列表中而不是进行函数调用。像这样的:

require(randomForest)
l<-list(ntree=10)
randomForest(mpg~.,mtcars,l[[1]])

但是,这不起作用。错误信息是:

Error in if (ncol(x) != ncol(xtest)) stop("x and xtest must have same number of columns") : argument is of length zero

这表示randomForest的参数xtest=NULL设置为10,而不是ntree。

这是为什么呢?如何将参数 ntree 作为列表元素传递?

谢谢。

【问题讨论】:

  • 谢谢。确实如此,但我想在列表中指定应该设置哪个参数。

标签: r parameters


【解决方案1】:

您可以使用do.call 来完成此操作,但您必须调整输入参数的方式。

do.call(randomForest, list(formula=as.formula(mpg~.), data=mtcars, ntree=10))

打印的输出没有那么漂亮,但最后,你得到了

               Type of random forest: regression
                     Number of trees: 10
No. of variables tried at each split: 3

          Mean of squared residuals: 9.284806
                    % Var explained: 73.61

如果你保存返回的对象,它的值与你输入的一样。

您也可以提前存储列表

l <- list(formula=as.formula(mpg~.), data=mtcars, ntree=10)
myForest <- do.call(randomForest, l)

【讨论】:

    最近更新 更多