Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

As we all know that we can pass functions into other functions, but what I want is to pass an "object" like variable into a function with other functions that are bound to the 'object'. Here is what I mean:

model1.calculation1 = function() {

    print( "model1.calculation1" )

}

model2.caclulation1 = function() {

    print( "model2.calculation2" ) 

}

runModel = function( model ) {

    model.calculation1() 

}

runModel( model1 )

runModel( model2 )

 The error message is as follows:

Error in model.calculation1() : 

  could not find function "model.calculation1"

Note: I am not doing anything to instantiate any model1 or model2 before binding a function to them. Is there a way to perform this? 

1 Answer

0 votes
by (108k points)

First let me declare the model1 and mode2:

model1 <- lm(mpg~hp, data=mtcars)

model2 <- lm(mpg~hp+am, data=mtcars)

Now after that I think you need to use substitute() to call the model and have your desired output:

runModel = function( model ) {

  s <- substitute(model)

  if(s=="model1")

    model1.calculation1() 

  else

    model2.calculation1() 

}

runModel( model1 )

# [1] "model1.calculation1"

runModel( model2 )

# [1] "model2.calculation2"

If you are a beginner and want to know more about R then do check out the R programming tutorial that will help you in understanding R from scratch.

Related questions

Browse Categories

...