[R] How to pass selection criteria in a function

Charles C. Berry cberry at tajo.ucsd.edu
Wed Dec 1 19:12:51 CET 2010


On Wed, 1 Dec 2010, CMcCarthy at bmcc.cuny.edu wrote:

> Hi,
> Suppose I have the following data
>
> name     score
> Abel        88
> Baker      54
> Charlie    77
>
> stored a  table called myData.
>
>
> I want to write a function that will create a table which is a subset of myData containing those have a score > 75.
>
> I know I can do this with the following command:
> subset(myData, score > 75)
>
> But I would like to do this via a function, something like:
>
> newTable <- function( data,  criteria){
>                     subset( data, criteria) }
>
> and then calling:     newTable(myData, score > 75)
>
> But this doesn't work. I am sure there is a simple way to do this,
> but I am stuck! Please help. Thanks!

Simple? Maybe not so much!

You are trying to pass objects without evaluating them. subset is rather 
special in the way it works. Here is one way:

> foo <- function(x,...){
+ mc <- match.call()
+ mc[[1]] <- as.name("subset")
+ eval(mc)
+ }
> foo(iris, Petal.Width>2.4 )
     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
101          6.3         3.3          6.0         2.5 virginica
110          7.2         3.6          6.1         2.5 virginica
145          6.7         3.3          5.7         2.5 virginica


Reading the code at the top of lm shows how this kind of strategy can be 
used.

You might look at

 	?bquote

for another way to skin this cat.


HTH,

Chuck

>
>
> Chris McCarthy, PhD
> Department of Mathematics BMCC
> Office: N522   Extension: 5235
> cmccarthy at bmcc.cuny.edu
> 	[[alternative HTML version deleted]]
>
>

Charles C. Berry                            Dept of Family/Preventive Medicine
cberry at tajo.ucsd.edu			    UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list