1

I currently set up a function which takes another function as an argument. I am trying to create this function to loop over the function it took as an argument.

However, with the way I set it up, it seems like it only really runs the function once, as it should be dependent on a random seed but it keeps coming back with the exact same value.

The only way I found to solve this was to not have the function as an argument but to hard code it in to the function, but this is not really what I want to do.

Here is my code:

runModel <- function(model,runs){
  b = c()
  for (i in 1:runs){
    a <- model$lambda.min
    b <- append(b,a)
  }
  return (c(mean(b),sd(b)))
}

cvModel = cv.glmnet(predictors,outcome,family=c("binomial"),alpha=.9,nfolds=20)

runModel(cvModel,20)

1 Answer 1

3

I don't know what are your objects 'predictors' or 'outcome' but it looks like your passing the result of your function cv.glmnet rather than the expression of your function to your runModel function.

One way to run the function at each loop could be to rewrite your function to pass function name and arguments:

runModel <-function(fun,runs,predictors,outcome,family=c("binomial"),alpha=.9,nfolds=20){
  b = c()

  model <- fun(predictors,outcome,family,alpha,nfolds)
  for (i in 1:runs){
    a <- model$lambda.min
    b <- append(b,a)
  }
  return (c(mean(b),sd(b)))
}

runModel(cv.glmnet,20, predictors,outcome,family=c("binomial"),alpha=.9,nfolds=20)
4
  • Instead of assigning the function to cvModel, I tried just typing it all out as the argument itself, but that did not work (code at end). I thought that would fix what you identified, but it does not seem to. Could you perhaps explain why that did not work? (code: runModel(cv.glmnet(predictors,outcome,family=c("binomial"),alpha=.9,nfolds=20),20))
    – evt
    Feb 4, 2015 at 6:58
  • 1
    @xraynaud I would suggest using ... that gets passed to cv.glmnet rather than explicitly producing the formal arguments. Feb 4, 2015 at 6:59
  • @fg nu true. This would make the run model function more general.
    – xraynaud
    Feb 4, 2015 at 7:02
  • @EvKohl if you did not modified the runmodel function, than the problem is still the same. The 'model' variable in your loop always contains the same data because the cv.glmnet function has been executed only one time.
    – xraynaud
    Feb 4, 2015 at 7:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.