[R] lapply and aggregate function

David Freedman 3.14david at gmail.com
Tue Feb 3 16:24:58 CET 2009


You might want to look at the doBy package

For (1), you could use
summaryBy(value~Light+Feed,data=myD, FUN=mean)

and for (2), the transformBy function would be helpful

David Freedman


Patrick Hausmann wrote:
> 
> Dear list,
> 
> I have two things I am struggling...
> 
> # First
> set.seed(123)
> myD <- data.frame( Light = sample(LETTERS[1:2], 10, replace=T),
>                      Feed  = sample(letters[1:5], 20, replace=T),
>                      value=rnorm(20) )
> 
> # Mean for Light
> myD$meanLight <- unlist( lapply( myD$Light,
>                          function(x) mean( myD$value[myD$Light == x]) ) )
> # Mean for Feed
> myD$meanFeed  <- unlist( lapply( myD$Feed,
>                          function(x) mean( myD$value[myD$Feed == x]) ) )
> myD
> 
> # I would like to get a new Var "meanLightFeed"
> # holding the "Group-Mean" for each combination (eg. A:a = 0.821581)
> # by(myD$value, list(myD$Light, myD$Feed), mean)[[1]]
> 
> 
> # Second
> set.seed(321)
> myD <- data.frame( Light = sample(LETTERS[1:2], 10, replace=T),
>                      value=rnorm(20) )
> 
> w1 <- tapply(myD$value, myD$Light, mean)
> w1
> # > w1
> #         A          B
> # 0.4753412 -0.2108387
> 
> myfun <- function(x) (myD$value > w1[x] & myD$value < w1[x] * 1.5)
> 
> I would like to have a TRUE/FALSE-Variable depend on the constraint in
> "myfun" for each level in "Light"...
> 
> As always - thanks for any help!!
> Patrick
> 
> ______________________________________________
> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/lapply-and-aggregate-function-tp21811834p21812057.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list