[R] Data frame column name as function argument?

bamsel benamsel at gmail.com
Tue Sep 22 23:07:28 CEST 2009


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)

> #How would I set up this syntax?
> #Thanks very much in advance. 
> # - Ben -
> 
-- 
View this message in context: http://www.nabble.com/Data-frame-column-name-as-function-argument--tp25530907p25530907.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list