[R] aggregate, by, *apply

Mark Ebbert Mark.Ebbert at hci.utah.edu
Wed Sep 15 23:45:31 CEST 2010


Dear R gurus,

I regularly come across a situation where I would like to apply a function to a subset of data in a dataframe, but I have not found an R function to facilitate exactly what I need. More specifically, I'd like my function to have a context of where the data it's analyzing came from. Here is an example:

### BEGIN ###
func<-function(x){
	m<-median(x$x)
	if(m > 2 & m < x$y){
		return(T)
	}
	return(F)
}

tmp<-data.frame(x=1:10,y=c(rep(34,3),rep(35,3),rep(34,4)),z=c(rep("a",3),rep("b",3),rep("c",4)))
res<-aggregate(tmp,list(z),func)
### END ###

The values in the example are trivial, but the problem is that only one column is passed to my function at a time, so I can't determine how 'm' relates to 'x$y'. Any tips/guidance is appreciated.

Mark T. W. Ebbert


More information about the R-help mailing list