[R] performing operations on a dataframe

jim holtman jholtman at gmail.com
Thu Nov 5 21:04:17 CET 2009


try this:

> x <- read.table(textConnection("Year SpA
+ 2000  0
+ 2000  2
+ 2000  1
+ 2001  8
+ 2001  2
+ 2001  0
+ 2001  0
+ 2002  1
+ 2002  2"), header=TRUE)
> closeAllConnections()
> # convoluted if you want a 'function' for each year
> l.func <- list('2000'=function(x) x / 146,
+                '2001'=function(x) x / 237,
+                '2002'=function(x) x/ 42)
> # split the data.frame and process
> result <- lapply(split(x, x$Year), function(.yr){
+     # call function based on year
+     cbind(.yr, func=l.func[[as.character(.yr$Year[1])]](.yr$SpA))
+ })
> do.call(rbind, result)
       Year SpA        func
2000.1 2000   0 0.000000000
2000.2 2000   2 0.013698630
2000.3 2000   1 0.006849315
2001.4 2001   8 0.033755274
2001.5 2001   2 0.008438819
2001.6 2001   0 0.000000000
2001.7 2001   0 0.000000000
2002.8 2002   1 0.023809524
2002.9 2002   2 0.047619048
>
> # a more reasonable way
> l.div <- c('2000'=146, '2001'=237, '2002'=42)
> x$div <- x$SpA / l.div[as.character(x$Year)]
> x
  Year SpA         div
1 2000   0 0.000000000
2 2000   2 0.013698630
3 2000   1 0.006849315
4 2001   8 0.033755274
5 2001   2 0.008438819
6 2001   0 0.000000000
7 2001   0 0.000000000
8 2002   1 0.023809524
9 2002   2 0.047619048
>


On Thu, Nov 5, 2009 at 1:30 PM, Lanna Jin <lannajin at gmail.com> 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?
>
> Thanks for your answer in advance!
>
>
> Lanna
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list