[R] Help with using 'get' function and variable scope

From: Peter Waltman <peter.waltman_at_gmail.com>
Date: Thu, 17 Apr 2008 17:37:58 -0400

Hi -

I'm having a really hard time w/understanding R's get function, and would appreciate any help with this.

Specifically, I'm using a for loop to call a function. I'd like the function to have access to the variable being incremented in the for-loop, i.e.

t.fn <- function() return( get( "i" ) )

t.fn2 <- function() {
for ( i in 1:5 )

     cat( t.fn(), "\n" )


However, I keep getting err msg's from the 'get' function about how it can't find the 'i' variable.

I've tried various combinations w/in the get fn, i.e. passing inherits=T (should be the default val according to R's help) and envir=sys.frame().

As I understand it, 'get' should search the enclosing environments, which I assume would be the call-stack of the functions. If not, could someone clarify?



p.s. when I define t.fn to be:

 t.fn<- function() {

    for ( j in sys.nframe():0 ) cat( j,":",ls( sys.frame( j ) ), "\n" ) }
and call that in t.fn2(), I do eventually see the 'i' variable, i.e.
> t.fn2()

2 : j
1 : i
0 : test t.fn t.fn2 t.fn3

	[[alternative HTML version deleted]]

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 17 Apr 2008 - 22:05:54 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 18 Apr 2008 - 00:30:30 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive