Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下片段:
y <- 1 g <- function(x) { y <- 2 UseMethod("g") } g.numeric <- function(x) y g(10) # [1] 2
我不明白,为什么可以访问yin g.numeric <- function(x) y。据我了解,y 的范围正好在泛型的定义范围内(g <- ...)。谁能向我解释一下,这怎么可能?
y
g.numeric <- function(x) y
(g <- ...)
此行为的描述可以在?UseMethod帮助页面中找到
?UseMethod
UseMethod 创建一个新的函数调用,其参数在进入泛型时匹配。在调用 UseMethod 之前定义的任何局部变量都将保留
因此,在函数调用UseMethod中定义的任何局部变量都作为局部变量传递给下一个函数。你可以看到这个
UseMethod
g.numeric <- function(x) ls() #lists all variables in current environment g(10) # [1] "x" "y" g.numeric(10) # [1] "x"