[R] tapply and grouping

Patrick Hausmann Patrick.Hausmann at uni-bremen.de
Sat May 17 20:04:35 CEST 2008


Hello all,

I have a df like this:

w <- c(1.20, 1.34, 2.34, 3.12, 2.89, 4.67, 2.43,
        2.89, 1.99, 3.45, 2.01, 2.23, 1.45, 1.59)
g <- rep(c("a", "b"), each=7)
df <- data.frame(g, w)
df

# 1. Mean for each group
tapply(df$w, df$g, function(x) mean(x))

# 2. Range for each group - fix value 0.15
tapply(df$w, df$g,
        function(x)
        x[(x > mean(x) - 0.15) &
          (x < mean(x) + ( 1 - 0.15 ))])

Now my question: How can I use different values of 0.15 for
each group. As a result of a calculation I have an object
"vari":

  > vari
     a    b
  0.41 0.08

  > str(vari)
   num [, 1:2] 0.41 0.08
   - attr(*, "dimnames")=List of 1
    ..$ : chr [1:2] "a" "b

So, I wanted to use 0.41 for group "a" and 0.08 for "b"
instead of 0.15...

Thanks for any help!!
Patrick



More information about the R-help mailing list