Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of methods invoked by UseMethod

Tags:

oop

r

generics

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?

like image 866
Evan Aad Avatar asked Dec 28 '13 19:12

Evan Aad


1 Answers

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
like image 180
Joshua Ulrich Avatar answered Oct 14 '22 21:10

Joshua Ulrich