[R] turning off automatic coersion from list to matrix

Gabor Grothendieck ggrothendieck at myway.com
Tue Aug 17 07:16:57 CEST 2004


HENRIKSON, JEFFREY <JEFHEN <at> SAFECO.com> writes:

: 
: Hello,
: 
: I am having trouble understanding how R is coercing between matrices and
: lists in the following example.  I have an aggregate behavior I like:
: 
: aggregate(a[,"num"],by=list(product=a[,"product"],region=a[,"region"]),
: sum)
: 
: Now in reality I have more columns than just product and region, and
: need to pick different combinations.  So I want to abstract this into a
: function.  Example use:
: 
: myagg(a,c("product","region"))
: 
: But I am having trouble because by= requires a list and apply and sapply
: seem to cast things back to the "matrix" type automatically.  Can I turn
: this off?  Eg:
: 
: data.class(sapply(c("product","region"),function(i) {a[,i]}))
: [1] "matrix"
: 
: whereas this would be acceptable to by=
: 
: data.class(list(product=a[,"product"],region=a[,"region"]))
: [1] "list"


I think you are looking for lapply but, actually, its even easier.

Note that a data frame is *already* a list thus you can do things
like this:

data(warpbreaks)
aggregate(warpbreaks[,"breaks",drop=F], warpbreaks[,c("wool","tension")], mean)

or you can use numeric indices like this:

aggregate(warpbreaks[,1,drop=FALSE], warpbreaks[,2:3], mean)




More information about the R-help mailing list