user7669
user7669

Reputation: 733

How to plot a caret train object in a function

I want to write e function that trains a regression model using the train function of the caret package and plots the resampling profile. My problem is that no plot is shown and no error is thrown. This should be a reproducible example:

trFun <- function(){
  library( caret )
  library( mlbench )
  data( BostonHousing )

  lmFit <- train(
    medv ~ .,
    data=BostonHousing,
    method="pls"
  )

  #trellis.par.set( caretTheme() )
  plot( lmFit )

  lmFit
}

fit <- trFun()

plot( fit )

So plot( lmfit ) inside trFun doesn't plot anything, while plot( fit ) outside the function does the plot. The trellis.par.set( caretTheme() ) statement seems to be irrelevant.

My question is: how can I plot the resampling profile inside trFun?

This is the sessionInfo() output:

R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.4.3 tools_3.4.3    yaml_2.1.16

Upvotes: 0

Views: 788

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24252

Try this:

trFun <- function() {
  library( caret )
  library( mlbench )
  data( BostonHousing )

  lmFit <- train(
    medv ~ .,
    data=BostonHousing,
    method="pls"
  )

  #trellis.par.set( caretTheme() )
  print(plot( lmFit ))

  lmFit
}

trFun()

enter image description here

Upvotes: 1

Related Questions