[R] lapply and aggregate function

Patrick Hausmann Patrick.Hausmann at uni-bremen.de
Tue Feb 3 16:11:57 CET 2009


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



More information about the R-help mailing list