4 ms·
I'd like to see a detailed explanation of R's scoping. It's not just lexical scoping; callees can deliberately manipulate the scope their arguments are evaluate
by capnrefsmmat 12y ago
I'd like to see a detailed explanation of R's scoping. It's not just lexical scoping; callees can deliberately manipulate the scope their arguments are evaluated in, for example. So you can call a function and pass arguments that are available in local scope, but the arguments are lazily evaluated, and the callee might evaluate them in an entirely different scope.
Typically this is done for manipulating datasets. You might have a data frame with columns Width and Height, and so you want to be able to call do.stuff(Width, Height, data=foo), and have Width and Height automatically taken from within foo. But sometimes it crops up in unexpected places.
- claytonjy 12y agoAre you familiar with Hadley's Advanced-R book? You can buy a hardcopy, but it's free online: http://adv-r.had.co.nz http://adv-r.had.co.nz There's a section on lexical scoping, and lots of other non-basic stuff that is hard to find covered elsewhere at all, much less well. From what I've seen, this is absolutely the best reference for deep R stuff that exists.
- capnrefsmmat 12y agoI've seen it but haven't read in depth. Now that I see the scoping section I'll have to read through it.
- claytonjy 12y agoNow that it's in print I suspect updates are less frequent, but until a few months ago sections were being added and rewritten pretty frequently, so it might have things now that it didn't when you looked last
- rcthompson 12y agoYou can think of the lazily evaluated arguments feature a lot like lisp macros. Basically, any function in R can either get the value of its arguments (i.e. acting like a regular function) or it can get the unevaluated expression passed for that argument (i.e. acting like a lisp macro). So in your "do.stuff" example, it's not a matter of special scoping, per se. The do.stuff function is actually getting the symbols "Width" and "Height" and then choosing to evaluate them with the value of the data argument as the innermost scope.
- lispm 12y agoThat would be a FEXPR in Lisp, not a macro. In most actually used Lisp dialects, FEXPRs have been replaced with macros.
- rcthompson 12y agoAh, yes, you're correct. Regardless of how an R function treats its arguments, it returns a result directly, never an unevaluated expression like a lisp macro. I didn't even know about FEXPRs (my main lisp is emacs lisp).
- hadley 12y agoYes, r functions are very similar to fexprs