lexical scope in R

Godel

I recently learned that R has both lexical and dynamical scoping available, but that it uses lexical scope by default. The next case really confused me:

> x <- 1
> f <- function(y) { x + y }
> f(5)  # we expect 6    
[1] 6
> x <- 10
> f(5)  # shouldn't we again expect 6?
[1] 15

Shouldn't f be evaluated using the environment where (and at the time!) it was defined and not where it was called ? How is this lexical scope? Thanks!

user1317221_G
f <- function(y) { x + y }

was defined in the global environment and so for the parts not defined in the function itself (i.e.x), R looks to the global environment for them.

a=1
b=2
f<-function(x)
{
  a*x + b
}
g<-function(x)
{
  a=2
  b=1
  f(x)
}
# compare f(2) and g(2)

This example above is from here and gives a good discussion. Main point being, f() within g() ignores the definitions of a and b in g().


From the wiki on "Scope"

In object-oriented programming, dynamic dispatch selects an object method at runtime, though whether the actual name binding is done at compile time or run time depends on the language.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

What is the Lexical Scope in dart?

lexical scope in Javascript issue

Lexical environment and function scope

What is lexical scope?

Lexical scope of callback function

Lexical Scope in JavaScript

What is lexical scope in reactjs

Context and Lexical environment in the global scope and object scope

Lexical scoping and the <<- operator in R

How is block scope managed in the lexical environment?

Lexical scope, variable lifetime and promises in javascript

Unexpected output regarding JavaScript lexical scope

When is Lexical Scope for a function within a function determined?

Does lexical scope have a dynamic aspect?

How to capture in lexical scope in a Clojure macro?

Is it possible to change a lexical scope programmatically, in Javascript?

How lexical scope affects lambda function?

Scope, lexical environment and Execution Context in javascript

What is the mechanism for lexical scope binding inside object methods (Javascript)?

Is there a way to use named arrow function to maintain lexical scope inside an object?

How can I preserve lexical scope in TypeScript with a callback function

Does lexical scope can only be created between curly braces?

Arrow functions without block bodies do not create lexical scope, right?

Should this Perl 6 CATCH block be able to change variables in the lexical scope?

Why does an immutable borrow in a loop last outside of its lexical scope?

How exactly does a Closure remember its lexical scope?

ES6 arrow function and lexical scope inside a function

Parsing with Haskell/Megaparsec: StateT for building up local, lexical scope?

Share lexical scope between successive eval statements in perl