[R] performing operations on a dataframe
Uwe Ligges
ligges at statistik.tu-dortmund.de
Fri Nov 6 10:38:51 CET 2009
Jim Lemon wrote:
> 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.
Why not simply one function that uses the year as an argument and
switch() on the year inside? Seems to be somewhat shorter and less errpr
prone at the end.
Best,
Uwe Ligges
> Jim
>
> ______________________________________________
> R-help at 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.
More information about the R-help
mailing list