Reputation: 1180
I am new to R. I have googled my problem but found nothing addressing exactly what I'm looking for. I know you can pass functions into other functions, but I would like to pass an "object" like variable into a function with other functions 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 )
and the error message:
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 do this? Thanks!
Upvotes: 2
Views: 56
Reputation: 18598
I think you are looking for substitute
.
runModel = function( model ) {
s <- substitute(model)
if(s=="model1")
model1.calculation1()
else
model2.calculation1()
}
runModel( model1 )
# [1] "model1.calculation1"
runModel( model2 )
# [1] "model2.calculation2"
model1 <- lm(mpg~hp, data=mtcars)
model2 <- lm(mpg~hp+am, data=mtcars)
Upvotes: 3