Re: [R] bug in 'margins' behavior in reshape - cast

From: hadley wickham <>
Date: Wed, 30 Jul 2008 13:10:00 -0500

On Wed, Jul 30, 2008 at 12:41 PM, mfrumin <> wrote:
> I want the column that is never going to actually have the '(all)' level to
> not become of type factor. continuing the example:
> chick_m$diet = as.integer(as.character(chick_m$diet))
> is.factor(chick_m$diet) #returns FALSE
> is.factor(cast(subset(chick_m, time == 0), diet + chick ~ time, mean,
> margins="diet")$diet) #returns TRUE
> does that make sense? the way it works now, it totally screws things up
> when the column for which you get margins is not a factor. in my case, a
> date column.

Oh, I see what you mean. That's definitely a bug and I've added it my todo list. Unfortunately it's not a trivial fix, and I'm currently working on a major rewrite of reshape (among other things), so it may be a while before I get to it

I can only offered this rather hackish work around:

chick_m$diet <- as.integer(as.character(chick_m$diet)) out <- cast(subset(chick_m, time == 0), diet + chick ~ time, mean, margins="diet")

restore <- function(cast, molten) {
  vars <- names(out)[sapply(out, function(x) is.factor(x) && sum(x == "(all)") == 0)]

  for(var in vars) {
    m <- match(as.character(cast[[var]]), as.character(molten[[var]]))

    cast[var] <- molten[m, var]

restore(out, chick_m)



______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 30 Jul 2008 - 18:12:11 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 31 Jul 2008 - 10:33:01 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive