Contrast the following two code snippets:
1)
> y <- 1
> g <- function(x) {
+ y <- 2
+ UseMethod("g")
+ }
> g.numeric <- function(x) y
> g(10)
[1] 2
2)
> x <- 1
> g <- function(x) {
+ x <- 2
+ UseMethod("g")
+ }
> g.numeric <- function(y) x
> g(10)
[1] 1
In the first snippet, g.numeric's free variable (namely, "y") is evaluated in g's local environment, whereas in the second snippet, g.numeric's free variable (namely "x") is evaluated in the global environment. How so?
As it says in Writing R Extensions:
A method must have all the arguments of the generic, including … if the generic does.
Your second example does not (g(x)
vs g.numeric(y)
). If you redefine g <- function(y)
, everything works the same as your first example.
> x <- 1
> g <- function(y) {
+ x <- 2
+ UseMethod("g")
+ }
> g.numeric <- function(y) x
> g(10)
[1] 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With