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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to