[R] Using tapply

Chuck Cleland ccleland at optonline.net
Thu May 15 12:54:53 CEST 2008


On 5/15/2008 5:05 AM, Patrick Hausmann wrote:
> Dear list,
> 
> I have a dataframe like this:
> 
> w <- c(1.2, 1.34, 2.34, 3.12, 2.43, 1.99, 2.01, 2.23, 1.45, 1.59)
> g <- rep(c("a", "b"), each=5)
> df <- data.frame(g, w)
> df
> 
>> df
>    g    w
> 1  a 1.20
> 2  a 1.34
> 3  a 2.34
> 4  a 3.12
> 5  a 2.43
> 6  b 1.99
> 7  b 2.01
> 8  b 2.23
> 9  b 1.45
> 10 b 1.59
> 
> Using tapply to get the mean for each group:
> 
> vk  <- tapply(df$w, df$g, mean)
> vk
> #> vk
> #    a     b
> #2.086 1.854
> 
> Now I would like to get for each group the first value *greater*
> than the mean.
> So for "a" it should be 2.34 and for "b" 1.99.

tapply(df$w, df$g, function(x){x[x > mean(x)][1]})
    a    b
2.34 1.99

> 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. 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list