[R] performing operations on a dataframe

Jim Lemon jim at bitwrit.com.au
Fri Nov 6 01:12:32 CET 2009


On 11/06/2009 05:30 AM, Lanna Jin wrote:
> Hey all,
>
> I feel like the solution to this problem should be relatively simple, but
> for some reason I can't find answers or come up with my own solution.
>
> Given the dataframe:
> (SpA and SpB not important, want to look at distribution of cooccurance for
> each year)
>
> Year SpA SpB Coocc
> 2000  0
> 2000  2
> 2000  1
> 2001  8
> 2001  2
> 2001  0
> 2001  0
> 2002  1
> 2002  2
>
> How can I apply different functions to the Coocc of each year?
> (Note: Different lengths for each year, ie,
> length(Year==2000)!=length(Year==2001))
> For example, if Year==2000, function(x) x/146; if Year=2001, function(x)
> x/237; etc.
>
> I've figured out the long convoluted way, but since I plan to operate
> numerous transformations on the different years, is there some way to solve
> this in just a few steps?
>    
Hi Lanna,
Perhaps if you define your different functions like this:

transfun2000<-function(x) x/146
transfun2001<-function(x) x/237

and then write a function like this:

mytrans<-function(x) {
  yearlabels<-unique(x$Year)
  nyears<-length(yearlabels)
  transcooc<-rep(NA,nyears)
  for(i in 1:nyears) {
   cooc<-somefunction(x[x$Year == yearlabels[i],])
   transcooc[i]<-do.call(paste("transfun",yearlabels[i],sep=""),...)
  }
  return(transcooc)
}

although this is largely guesswork.

Jim




More information about the R-help mailing list