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

hadley wickham h.wickham at gmail.com
Wed Jul 30 20:10:00 CEST 2008


On Wed, Jul 30, 2008 at 12:41 PM, mfrumin <michael at frumin.net> 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]
  }
  cast
}

restore(out, chick_m)

Hadley


-- 
http://had.co.nz/



More information about the R-help mailing list