[Rd] [R] ave and factors with unused levels (PR#4753)

wolfram at fischer-zim.ch wolfram at fischer-zim.ch
Fri Oct 24 09:15:33 MEST 2003


[R 1.7.1 on linux]

There seems to be a problem when using ave() with a grouping factor
having a first level value which is not used in the data vector.

---- CODE ----------------
x <- data.frame( grp = factor( c(10,20,10,10), levels=c(99,10,20) ) )
x$val <- 10^( (nrow(x)-1) : 0 )
x$ave.factor <- ave( x$val, x$grp, FUN=sum )
x$ave.numeric <- ave( x$val, as.numeric( x$grp ), FUN=sum )
x

---- RESULT --------------
  grp  val ave.factor ave.numeric
1  10 1000        100        1011
2  20  100         NA         100
3  10   10        100        1011
4  10    1        100        1011


---- PROBLEM -------------
x$ave.numeric is correct, but x$ave.factor shows abitrary values.

---- OBSERVATIONS --------
If 99 is eliminated as level of x$grp, x$ave.factor is ok:
	x <- data.frame( grp = factor( c(10,20,10,10), levels=c(10,20) ) )

If 99 is the last level of x$grp, x$ave.factor is ok:
	x <- data.frame( grp = factor( c(10,20,10,10), levels=c(10,20,99) ) )

---- ---------------------

Wolfram Fischer



More information about the R-devel mailing list