Search code examples
rclassificationdo.call

Build a call to get expression for do.call execution


Giving this example:

lstParams <- list()
lstParams$formula <- as.formula("Sepal.Length ~ Sepal.Width + Petal.Length")                         
lstParams$data <- substitute(iris)
lstParams$distribution <- "bernoulli"

mdl <- do.call("gbm", lstParams)
mdl
gbm(formula=Sepal.Length ~ Sepal.Width + Petal.Length, distribution="bernoulli", 
    data=iris)
# A gradient boosted model with bernoulli loss function.
# 100 iterations were performed.
# There were 2 predictors of which 0 had non-zero influence.

I can get the call to gbm function by :

mdl$call
gbm(formula=Sepal.Length ~ Sepal.Width + Petal.Length, distribution="bernoulli", 
    data=iris)

Since some error can happen in: mdl<-do.call("gbm",lstParams) (e.g some NAs found in the target variable or wrong formula):

lstParams <- list()
lstParams$formula <- as.formula("Sepal.Length ~ Sepal.Width + Petal.Lengthx")                        
lstParams$data <- substitute(iris)
lstParams$distribution <- "bernoulli"

mdl <- do.call("gbm", lstParams)
# Error in eval(predvars, data, env) : object 'Petal.Lengthx' not found

I would like to get the call to gbm function in advance in order to debug it.

Is there any way to get that call before the execution? Thanks


Solution

  • as.call is your friend. quote function name as first list element first.

    lstParams <- list()
    lstParams$name <- quote(gbm::gbm)
    lstParams$formula <- as.formula("Sepal.Length ~ Sepal.Width + Petal.Length")                       
    lstParams$data <- substitute(iris)
    lstParams$distribution <- "bernoulli"
    g <- as.call(lstParams)
    

    Call

    g
    # gbm::gbm(formula = Sepal.Length ~ Sepal.Width + Petal.Length, 
    #          data = iris, distribution = "bernoulli")
    

    Evaluation

    eval(g)
    # gbm::gbm(formula = Sepal.Length ~ Sepal.Width + Petal.Length, 
    #          distribution = "bernoulli", data = iris)
    # A gradient boosted model with bernoulli loss function.
    # 100 iterations were performed.
    # There were 2 predictors of which 0 had non-zero influence.
    

    You can still use do.call.

    do.call("gbm", as.list(g)[-1])
    # A gradient boosted model with bernoulli loss function.
    # 100 iterations were performed.
    # There were 2 predictors of which 0 had non-zero influence.