# [Rd] Re: [R] ave and factors with unused levels (PR#4759)

wolfram at fischer-zim.ch wolfram at fischer-zim.ch
Fri Oct 24 16:43:44 MEST 2003

```The problem is solved in R 1.8.0.
[Excuse me for the previous message...]

Wolfram

>Date:    24.10.03 09:16 (+0200)
>From:    Wolfram Fischer - Z/I/M <wolfram at fischer-zim.ch>
>To:      wolfram at fischer-zim.ch
>Subject: [R] ave and factors with unused levels
>
> [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

```