Reputation: 87
I'm not that much of an OOP guy, so could someone please explain this simple concept in layman terms.
When I call foo.child from the foo.parent function, it seems to pass the A=7 argument down into the foo.child object and overrides or takes precedence over the A=3 default argument in foo.child as I would expect.
foo.parent <- function(A=7) foo.child(A)
foo.child <- function(A=3) 2+A
foo.parent(A=7)
#[1] 9
But when I instantiate it inside of foo.parent, the parameter A=7 does pass down or force the instantiated object to use A=7; instead it uses the child object's parameter of A=3
foo.child<-function(A=3) 2+A
foo.parent <- function(A=7){
foo.child(A=3)
}
foo.parent(A=7)
#[1] 5
Why does that happen? And what terminology would I use to describe the differences?
Upvotes: 0
Views: 373
Reputation: 60492
I think your problem is you don't quite understand how default arguments work. So
foo.child = function(A=1) 2+A
defines the function foo.child
that has a default argument A=1
. So,
foo.child()
gives 3. Now in this function
foo.parent = function(A=3){
foo.child(A=4)
}
you are always passing the value A=4
to the function foo.child
, hence,
foo.parent(A=7)
# 6
Also, when you are trying to figure out what is happening, it's helpful to have different values of A
Upvotes: 2
Reputation: 3380
In your second example you do not give a value to A
(At least not in such a way as you might thought). Try
foo.child<-function(A=3) 2+A
foo.parent<-function(A=7){
foo.child(A=A)
}
foo.parent(A=7)
foo.parent()
instead. So, you mix here two different A
s. The =
sign within a function
call defines, what happens if you do not give a value for that variable in the function call.
Upvotes: 2