获取一个调用对象,更改参数并使用新参数再次运行它 [英] get a call object, change parameters and run it again with the new parameters

查看:121
本文介绍了获取一个调用对象,更改参数并使用新参数再次运行它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从随机森林生成的模型.它的内部有一个称为call的属性,它将为我提供实际上是randomForest称为函数的内容.

I have a model generated from a random forest. Inside it, there is a attribute called call, that will give me the what was actually the randomForest called function.

我想获取此参数,从模型中删除一列,然后再次运行.

I want to get this parameter, remove one column from the model and run it again.

例如:

library(randomForest)
data(iris)
iris.rf <- randomForest(Species~.-Sepal.Length,  data=iris, prox=TRUE)
iris.rf$call

# want to remove the field Sepal.length as well
# the call should be then 
# randomForest(Species~.-Sepal.Length-Sepal.Width,  data=iris, prox=TRUE)

我尝试转换为列表,粘贴新的参数,然后再次将其添加到iris.rf [[2]],但它将粘贴到公式的所有部分.

I have tried converting to a list, pasting the new argument and then adding it again to iris.rf[[2]], but it paste in all parts of the formula.

我无法摆脱对类的调用,对其进行更改然后再调用eval()再次运行它.

I cannot get rid of the class call, to change it and then call eval() to run it again.

推荐答案

您可以在paste0对象上使用parse来获取新表达式.然后,您可以将该新对象评估为调用.

You could use parse on the paste0 object to get a new expression. You could then evaluate that new object as a call.

也许是这样的:

> iris.rf$call[[2]][3] <- parse(text = with(iris.rf, {
      paste0(call[[2]][3], " - ", rownames(importance)[1])
  }))
> eval(iris.rf$call)
#
# Call:
#  randomForest(formula = Species ~ . - Sepal.Length - Sepal.Width,      
#               data = iris, prox = TRUE) 
#                Type of random forest: classification
#                      Number of trees: 500
# No. of variables tried at each split: 1
#
#         OOB estimate of  error rate: 3.33%
# Confusion matrix:
#            setosa versicolor virginica class.error
# setosa         50          0         0        0.00
# versicolor      0         47         3        0.06
# virginica       0          2        48        0.04

请注意,尽管eval(parse(text = ...))确实可以很好地完成这项工作,但不建议这样做.

Note that eval(parse(text = ...)) is not something that is recommended, although it does work nicely for this job.

这篇关于获取一个调用对象,更改参数并使用新参数再次运行它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆