[R] prevent conversion to factors in aggregate?

Spencer Graves spencer.graves at pdf.com
Sun Nov 16 04:33:38 CET 2003


I don't know how to prevent aggregate from making factors of everything, 
but the following shows how to cast them back into what you want: 

 > DF1 <- data.frame(a=1:9, b=rep(letters[1:3], 3), d=rep(1:3, each=3))
 >
 > DF. <- aggregate(DF1$a, by=list(b=DF1$b, d=DF1$d), FUN=sum)
 > sapply(DF., class)
        b         d         x
 "factor"  "factor" "integer"
 >
 > DF.$bch <- as.character(DF.$b)
 > DF.$dn <- as.numeric(as.character(DF.$d))
 > sapply(DF., class)
          b           d           x         bch          dn
   "factor"    "factor"   "integer" "character"   "numeric"

How's this?  I just got this same result from S-Plus 6.1 and R 1.8.0. 
spencer graves

Jeff D. Hamann wrote:

>I've been trying to figure out how to prevent a column that is the result of
>an aggregate function call so that I can use it in further calculations. For
>example, I would like to aggregate the expf for the data.frame by sp
>(character) and dbh (double d=rounded to integer) using the command:
>
>
>  
>
>>st2 <- aggregate( ntrs$expf, by=list(sp=ntrs$sp,dbh=ntrs$dbh), sum )
>>st2$expf <- st2$x / 20
>>st2$basal.area <- st2$dbh^2 * st2$expf
>>    
>>
>Warning message:
>"^" not meaningful for factors in: Ops.factor(st2$dbh, 2)
>  
>
>
>attributes(st2$dbh) tell me the class is a factor. I would like to values to
>remain AsIs but cannot seem to figure out how to tell aggregate how to do
>that, or even handle the operation after the fact by converting or adding an
>extra column to the resulting data.frame.
>
>I've tried using I() with no luck
>
>  
>
>>st2 <- aggregate( ntrs$expf, by=list(sp=ntrs$sp,dbh=I(ntrs$dbh)), sum )
>>    
>>
>
>How can/do I "cast" the dbh factor into an integer in the data.frame?
>
>Thanks,
>Jeff.
>
>---
>Jeff D. Hamann
>Forest Informatics, Inc.
>PO Box 1421
>Corvallis, Oregon USA 97339-1421
>(office) 541-754-1428
>(cell) 541-740-5988
>jeff.hamann at forestinformatics.com
>www.forestinformatics.com
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>  
>




More information about the R-help mailing list