From murdoch at stats.uwo.ca  Thu Dec 24 01:31:31 2009
From: murdoch at stats.uwo.ca (Duncan Murdoch)
Date: Wed, 23 Dec 2009 19:31:31 -0500
Subject: [Rd] Locating code that is outside of functions in R scripts
In-Reply-To: <fb287d9d14fc581a6136541c2685b3b7@localhost>
References: <fb287d9d14fc581a6136541c2685b3b7@localhost>
Message-ID: <4B32B663.8080909@stats.uwo.ca>

On 23/12/2009 7:04 PM, gheine at mathnmaps.com wrote:
> Working with a number of scripts (text files with R commands) that I
> 
> "source" into R sessions from time to time.
> 
> The source() command is most convenient (at least for me) 
> 
> if it only loads function definitions, and doesn't otherwise change the
> 
> interactive environment.  For example, I might have a file that looks like
> 
> 
> 
> func1<-function() {
> 
>   code
> 
>   code
> 
>   code
> 
>   }
> 
> # this is a comment
> 
> 
> 
> A<-"this is code outside the function definitions";
> 
> 
> 
> func2<-function() {
> 
>    code
> 
> # a comment with a spurious } 
> 
>    code
> 
>    code
> 
>    }
> 
> 
> 
> I would like a quick-and-dirty script that finds the line beginnning with
> 
> "A", since it is R code outside of any function definition.
> 
> On the other hand it would ignore the two comment lines, and would not be
> 
> fooled by the spurious "}" in the second comment line.
> 
> Probably not too hard to put something like this together, but am making
> 
> this post in case it is something that has already been done.

You should call parse() to process the file, then examine the list of 
expressions that gets returned.  This function will recognize a function 
definition if it is the form above:

isfundef <- function(e) {
   identical(e[[1]], quote(`<-`)) && identical(e[[3]][[1]], 
quote(`function`))
}

but there are other ways to create functions which it will miss. 
Nevertheless, pasting your code into a file and doing this seems to give 
you what you want:

 > exprs <- parse("test.R")
 > lapply(exprs, isfundef)
[[1]]
[1] TRUE

[[2]]
[1] FALSE

[[3]]
[1] TRUE

 > exprs[[2]]
A <- "this is code outside the function definitions"

or

 > exprs[!unlist(lapply(exprs, isfundef))]
expression(A<-"this is code outside the function definitions")


Duncan Murdoch



[Rd] Locating code that is outside of functions in R scripts
Duncan Murdoch