Skip to content
Prev 308267 / 398503 Next

How to count rows with a condition

data[ ave(data$ac_name, data$ac_name, length) <= 5, ]
fails for two reasons:
  a) you need to label the FUN argument, FUN=length, since there
      is a ... in the middle of ave's argument list to catch all the grouping arguments
  b) the type of the first argument to needs to be compatible with
      the type of the return value of FUN().  If ac_name is a factor
      you get NA's and warnings, if it is character  the "<5" starts using
      character order instead of numerical order, leading to incorrect results
      because "11"<"5":
ac_name   n
1       Amos 101
2       Amos 102
3       Amos 103
12 Charlotte 112
13 Charlotte 113
... [ rows elided ] ...
22 Charlotte 122
ac_name  n
NA       <NA> NA
NA.1     <NA> NA
NA.2     <NA> NA
... [rows elided] ...
NA.21    <NA> NA
Warning messages:
1: In `[<-.factor`(`*tmp*`, i, value = 3L) :
  invalid factor level, NAs generated
2: In `[<-.factor`(`*tmp*`, i, value = 8L) :
  invalid factor level, NAs generated
3: In `[<-.factor`(`*tmp*`, i, value = 11L) :
  invalid factor level, NAs generated
4: In Ops.factor(ave(data$ac_name, data$ac_name, FUN = length), 5) :
  <= not meaningful for factors

That is why I made the first argument integer:
ac_name   n
1    Amos 101
2    Amos 102
3    Amos 103
  

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com