[R] scoping rules; summary

Uwe Ligges ligges at statistik.uni-dortmund.de
Tue Mar 18 09:37:49 CET 2003



Robin Hankin wrote:
> 
> Hi everyone
> 
> thanks for the replies.
> 
> The issue was NOT a font problem; I deliberately chose ll1 and l11 as
> examples of easily confused variable names (evidently these were too
> easily confused ;-).  The code snippet was written as intended, and
> increment() contained a deliberate, highlighted, bug.  I was asking
> for guidance on avoiding/finding this sort of coding error.
> 
> That was why I wrote "#bug here" in the original code, and why the
> function was called increment()---because the function should have
> incremented x by adding a variable whose value was 1 (of course, the
> function as written, contrary to the desired functionality of
> increment(), added a variable whose value was 2).  I guess I wasn't
> explicit enough here.  Sorry.
> 
> The fundamental problem was, how to tell that a variable being used in
> a function is not local?
> 
> One answer (thanks Patrick!): conflicts() shows masked objects on the
> search path, which is not quite what I need: I want some way to list
> all non-local variables that increment() uses in its body.
> 
> [The original variable names referred to genetic bandsharing data for
> possums, eg
> 
> coates.female.pouchyoung.allbands.method5
> and
> huapai.young.male.sibling.relatedness.method3
> and
> huapai.old.female.nonsibling.relatedness.justdarkbands.method1
> 
> ad nauseum...hence the need for shorter example variable names!]
> 
> ll1 <- 2          #sic
> increment <- function(x)
> {
>   l11 <- 1        #sic
>   return(x+ll1)   #sic; deliberate bug here (sic)
> }


I think you are looking for ls() together with the debugging tool
browser():

increment <- function(x){
  l11 <- 1
  browser()    # just for debugging
  return(x+ll1)
}
increment(1)
# Now the browser opens and you can look for objects in the current
enviroment with ls().


Uwe Ligges



> --
> 
> Robin Hankin, Lecturer,
> School of Geography and Environmental Science
> Tamaki Campus
> Private Bag 92019 Auckland
> New Zealand
> 
> r.hankin at auckland.ac.nz
> tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help



More information about the R-help mailing list