[R] Data frame column name as function argument?

David Winsemius dwinsemius at comcast.net
Tue Sep 22 23:38:56 CEST 2009


On Sep 22, 2009, at 5:07 PM, bamsel wrote:

>
> Any help is very much appreciated. The following is a toy example:
>
>> #1. Create a data frame with two named columns (x,y):
>> DF <- data.frame(cbind(x=1:5, y=6:10))
>> DF
>  x  y
> 1 1  6
> 2 2  7
> 3 3  8
> 4 4  9
> 5 5 10
>
>> #2. Define a function to compute the sum of a given column:
>> foo.fnc = function(i){
> +            return(sum(DF[ ,i]))
> + }
>>
>> #3. Call the function to get the mean of column 1, for example:
>> foo.fnc(1)
> [1] 15
>>
>> # Now, what I really want is to be able to use a column name as the
>> argument
>> # That is, something like:
>>
>> #  foo.fnc = function(colname)
>> # And calling it:
>> #   foo.fnc(DF$x)

That would just be giving the column vector itself to the function, so  
the function could be as simple as:

foo.fnc <- function(x) sum(x)

Had you wanted to give two arguments, it could be thus:

 > foo2.fnc <- function(dfrm, cname) sum(dfrm[,cname])
 > foo2.fnc(DF, "x")
[1] 15

-- 
David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list