Scope of Methods Used by UseMethod

Contrast the following two code snippets:

one)

> 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 fragment, g.numeric free variable (namely, “y”) is evaluated in the g local environment, while in the second fragment, g.numeric free variable (namely, “x”) is evaluated in the global environment. How is this?

+7
generics oop r
source share
1 answer

As stated in Writing Extensions V :

A method must have all arguments of a general type, including ... if a generic type.

In your second example, no ( g(x) vs g.numeric(y) ). If you override g <- function(y) , everything will work just like your first example.

 > x <- 1 > g <- function(y) { + x <- 2 + UseMethod("g") + } > g.numeric <- function(y) x > g(10) [1] 2 
+7
source share

All Articles