[R] lapply and aggregate function
hadley wickham
h.wickham at gmail.com
Tue Feb 3 17:25:12 CET 2009
> # 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"...
You could use ddply from the plyr package for this:
install.packages("plyr")
library(plyr)
ddply(myD, .(Light), transform,
constraint = value > mean(value) & value < mean(value) * 1.5)
This applies the transform function to each subset defined by Light,
and then joins all the pieces back together in a single data frame.
You can use a similar approach for the other parts:
myD <- ddply(myD, .(Light), transform, meanLight = mean(value))
myD <- ddply(myD, .(Feed), transform, meanFeed = mean(value))
myD <- ddply(myD, .(Feed, Light), transform, meanFeedLight = mean(value))
Hadley
--
http://had.co.nz/
More information about the R-help
mailing list