Skip to content
Prev 243657 / 398513 Next

How to pass selection criteria in a function

On Dec 1, 2010, at 1:12 PM, Charles C. Berry wrote:

            
I've never really understood how to use browser() to develop or  
resolve problems with function definitions. Chuck's comments pointing  
to the subset function offered another opportunity to teach myself  
something new. Here's the console transcript:

 > newTable <- function( data, criteria){  crit <-  
substitute(criteria);browser()}
# Obviously not a complete function
 > newT <- newTable(myData, score < 75)
Called from: newTable(myData, score < 75) #so far so good
Browse[1]> criteria                  # I realize now that this should  
have been "crit"
Error: object 'score' not found      # took another look at subset()  
code
Browse[1]> newTable <- function( data, criteria){  crit <-  
substitute(criteria); logvec <- eval(crit, data, parent.frame());  
browser()}
Browse[1]> criteria              # still didn't catch on that "crit"  
was the local object to examine
Error: object 'score' not found  # just slow I guess.
In addition: Warning message:
restarting interrupted promise evaluation
Browse[1]> c      # was worried the the redefinition might not take  
effect at the top-level

# Try # 2
 > newTable <- function( data, criteria){  crit <-  
substitute(criteria); logvec <- eval(crit, data, parent.frame());  
browser()}
 > newT <- newTable(myData, score < 75)
Called from: newTable(myData, score < 75)
Browse[1]> logvec
[1] FALSE  TRUE FALSE                # now we're getting results
Browse[1]> return(data[logvec, ])    # see if the naive next step works
 > newT
    name score
2 Baker    54                        # very promising
 > newTable <- function( data, criteria){  crit <-  
substitute(criteria); logvec <- eval(crit, data, parent.frame());  
return(data[logvec, ])}
 > newT <- newTable(myData, score < 75)
 > newT                                # SUCCESS
    name score
2 Baker    54

There is not much in the way of error checking, but it seems to be a  
reasonable start (and looks to offer an example, albeit with a some  
newbie errors, of an extremely useful R tool.)
Thanks, Chuck.