[R] aggregate factor

Bill Szkotnicki bszk at uoguelph.ca
Fri Sep 7 21:09:43 CEST 2007


Hi,
I am using aggregate to compute means for later plotting.
There are two factors involved and the problem is that the values of the 
second factor ( Age ) in the means are not in the right order because 
"10" comes inbetween "1" and "2"
What I really want is the numeric value of Age but as.numeric and 
as.integer returns the level value instead.
Is there a way to easily get the numeric value?
I am using Windows R 2.5.1

Thanks,

 > str(fishdata)
'data.frame':   372 obs. of  6 variables:
 $ Lake: Factor w/ 3 levels "EVANS","JOLLIET",..: 3 3 3 3 3 3 3 3 3 3 ...
 $ Age : int  1 1 1 1 1 1 1 1 1 1 ...
 $ TL  : int  132 120 125 115 130 120 115 110 117 116 ...
 $ W   : int  10 10 10 10 10 10 10 10 10 20 ...
 $ Sex : Factor w/ 3 levels "F","I","M": 1 1 2 2 2 1 1 1 2 2 ...
 $ WT  : num  0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 ...
 > fishdatameans=aggregate(fishdata$TL, list(Lake = fishdata$Lake, 
Age=fishdata$Age), mean)

#  Now Age is a Factor but 10 is in the wrong position.
 > fishdatameans$Age
 [1] 0  1  1  1  2  2  2  3  3  3  4  4  4  5  5  6  6  6  7  8  9  10
Levels: 0 1 10 2 3 4 5 6 7 8 9

 > as.numeric(fishdatameans$Age)
 [1]  1  2  2  2  4  4  4  5  5  5  6  6  6  7  7  8  8  8  9 10 11  3
 >
# What I want  is ---->   0  1  1  1  2  2  2  3  3  3  4  4  4  5  5  
6  6  6  7  8  9  10

Bill



More information about the R-help mailing list