What does ‘length of ‘dimnames’ [1] not equal to array extent’ mean?

OK, I can reproduce this from scratch, with reshape (but not with reshape2). Something is indeed getting mangled by head().

d <- data.frame(time=rep(1:10,10),x=rep(1:10,each=10),y=1:100)
library(reshape2)
str(dcast(d,time~x))  ## regular data frame
detach("package:reshape2")
library(reshape)
str(z <- cast(d,time~x))
matplot(head(z))  ## error

The specific problem is an interaction between utils::head.data.frame, which drops pieces of the object without keeping a completely consistent internal structure, and as.matrix.cast_df (called by matplot), which assumes that structure is there.

Adding the following method seems to fix the problem.

head.cast_df <- function (x, n = 6L, ...)  {
    stopifnot(length(n) == 1L)
    n <- if (n < 0L) {
        max(nrow(x) + n, 0L)
    } else min(n, nrow(x))
    h <- x[seq_len(n), , drop = FALSE]
    ## fix cast_df-specific row names element
    attr(h,"rdimnames")[[1]] <- rdimnames(h)[[1]][seq_len(n),,drop=FALSE]
    h
}

It might be worth contacting the maintainer about this, although the reshape package is (I think) deprecated in favor of reshape2 …

An alternative workaround is to switch from reshape::cast to reshape2::dcast if possible …

Leave a Comment