hadley/reshape — pull request #10 by BrianDiggs (2011-11-04 19:19:07+00:00)
Title: Allow value to be factor when dcast

# Bug

When the value from a `melt` is a factor, attempting to `dcast` it into a form with multiple columns threw an error

# Reproducible code

```r
df <- data.frame(fac1 = letters[1:4], fac2 = LETTERS[1:4], x = factor(1:4))
mx <- melt(df, id = c("fac1", "fac2"), measure.var = "x")
c2 <- dcast(mx, fac1 ~ fac2 + variable)
```

# Produced output

```r
Error in names(data) <- array_names(res$labels[[2]]) :
'names' attribute [4] must be the same length as the vector [1]
```

# Problem

In `dcast`, (part of) the results from (the internal) `cast` are passed to `as.data.frame`. This part is created by directly adding a `dim` attribute to the structure of the ordered data. When this is added to a factor, it creates a factor with dimensions, but one that does not have class matrix. Rather, it has class factor. Thus when `as.data.frame` is called on it, it actually creates an invalid data.frame. (This may be a separate bug in
`as.data.frame.factor` which assumes that the factor does not have a `dim` attribute.)

# Solution

Rather than allow `as.data.frame` to dispatch, call `as.data.frame.matrix` explicitly. This is reasonable since we are expecting a matrix shape.