You could use sapply to pass in a vector of numbers (for column numbers) or
characters (for column names) and index the columns of the input data.
Something like this:-
> innerFun <- function(i, df) {
if (i == 1) mean(df[[i]])
else median(df[[i]])
}
> sapply(1:length(myDf), innerFun, df=myDf)
Not as efficient as apply for larger data structures I'd imagine, since
you're passing the entire dataset in each time ...
Rich.
-----Original Message-----
From: s-news-owner@lists.biostat.wustl.edu
[mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Schwarz,Paul
Sent: 11 February 2006 02:19
To: s-news@lists.biostat.wustl.edu
Subject: [S] identifying which column/row is passed in calls to apply()
S-News readers,
How would I identify which column (or row) is being operated on in a
call to the function specified in apply()? That is, if I wanted to
perform some column-specific (or row-specific) operation, how do I
identify which column/row is being passed to the function that's
specified in the call to apply(), where the number of columns ranges
from 1 to ncol(mymat)?
apply( mymat, 2, function(x){ ? } )
I suspect that this is easy, but I'm drawing a blank on how to do this.
Thanks a lot everyone.
-Paul
--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu. To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message: unsubscribe s-news
|