5

下面是一个示例会话的输出片段。在其中,我使用该函数创建了一个矩阵,matrix()然后简单地将其转换为具有该as.data.frame()函数的数据框。在第二部分中,我还创建了一个矩阵,但通过不同的过程(我想要工作的过程),但即使str()给了我类似的输出,我在转换为数据帧时也会出错。有任何想法吗?

编辑:最后,我添加了一行,将矩阵(重新)转换为矩阵,然后将其转换为数据框。它可以工作,但我不应该根据我在无法转换为数据帧的str()输出中看到的内容重新转换。test_mx所以我知道如何解决,但我不明白为什么我需要做那个额外的步骤。

R version 2.15.2 (2012-10-26) -- "Trick or Treat"

> library(reshape)
> ## This works
> ## ==========
> tmx = matrix(1:12*0.1, ncol=4)
> rownames(tmx) = c("A", "B", "C")
> colnames(tmx) = 0:3
> tmx
    0   1   2   3
A 0.1 0.4 0.7 1.0
B 0.2 0.5 0.8 1.1
C 0.3 0.6 0.9 1.2
> 
> str(tmx)
 num [1:3, 1:4] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "A" "B" "C"
  ..$ : chr [1:4] "0" "1" "2" "3"
> as.data.frame(tmx)
    0   1   2   3
A 0.1 0.4 0.7 1.0
B 0.2 0.5 0.8 1.1
C 0.3 0.6 0.9 1.2
> 
> 
> 
> ## This does not
> ## =============
> t = 0:3
> thesd = 0.1
> dat = data.frame(
+     a1 = sin(2*pi*t/length(t)) + rnorm(t, sd=thesd),
+     b1 = sin(2*pi*t/length(t) - pi) + rnorm(t, sd=thesd),
+     c1 = sin(2*pi*t/length(t) - pi/2) + rnorm(t, sd=thesd),
+     t  = t
+ )
> 
> test_mx = cast(melt(dat, id.vars="t"), variable ~ t)
> tmp_rownames = as.character(test_mx[,1])
> test_mx = test_mx[,-1]
> tmp_colnames = colnames(test_mx)
> test_mx = as.matrix(test_mx)
> rownames(test_mx) = tmp_rownames
> colnames(test_mx) = tmp_colnames
> 
> str(test_mx)
 num [1:3, 1:4] 0.06211 -0.00596 -1.09718 1.1555 -0.96443 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "a1" "b1" "c1"
  ..$ : chr [1:4] "0" "1" "2" "3"
> as.data.frame(test_mx)
Error in data.frame(rrownames(x), unx, check.names = FALSE) : 
  arguments imply differing number of rows: 0, 3
> 
> ## But this does work
> as.data.frame(as.matrix(test_mx))
             0           1           2           3
a1 -0.16166693  0.97479282  0.01471777 -1.01517539
b1 -0.01012797 -0.97745698 -0.12667287  0.96542412
c1 -1.07217297  0.06783235  1.12068282 -0.02012263

> ## why?
4

2 回答 2

11

虽然@agstudy 的回答解决了您的问题并让您了解最新的软件包,但它并没有试图理解为什么会发生这种情况。

要了解原因,请退回到您的线路test_mx = cast(melt(dat, id.vars="t"), variable ~ t)。我将在这里创建两个对象,以便我们进行一些比较:

test_mx <- test_mx_cast <- cast(melt(dat, id.vars="t"), variable ~ t)
class(test_mx)
# [1] "cast_df"    "data.frame"
class(test_mx_cast)
# [1] "cast_df"    "data.frame"

唔。这cast_df门课是什么?事实证明,“重塑”方法已经消失并定义了几种新方法。参见,例如,methods(as.data.frame)methods(as.matrix)

> methods(as.matrix)
[1] as.matrix.cast_df     as.matrix.cast_matrix as.matrix.data.frame  as.matrix.default    
[5] as.matrix.dist*       as.matrix.noquote     as.matrix.POSIXlt     as.matrix.raster*    

   Non-visible functions are asterisked
> methods(as.data.frame)
 [1] as.data.frame.aovproj*        as.data.frame.array           as.data.frame.AsIs           
 [4] as.data.frame.cast_df         as.data.frame.cast_matrix     as.data.frame.character      
 [7] as.data.frame.complex         as.data.frame.data.frame      as.data.frame.Date           
[10] as.data.frame.default         as.data.frame.difftime        as.data.frame.factor         
[13] as.data.frame.ftable*         as.data.frame.function*       as.data.frame.idf*           
[16] as.data.frame.integer         as.data.frame.list            as.data.frame.logical        
[19] as.data.frame.logLik*         as.data.frame.matrix          as.data.frame.model.matrix   
[22] as.data.frame.numeric         as.data.frame.numeric_version as.data.frame.ordered        
[25] as.data.frame.POSIXct         as.data.frame.POSIXlt         as.data.frame.raw            
[28] as.data.frame.table           as.data.frame.ts              as.data.frame.vector         

   Non-visible functions are asterisked

请注意上面 ^^ 的第一种和第二种方法as.matrix以及 的第四种和第五种方法as.data.frame

这是什么意思?好吧,您在创建后写了几行test_mx以将您的转换data.framematrix. 这主要是因为您想确保您的第一列最终成为rownames并且没有将整个矩阵强制转换为字符矩阵。

tmp_rownames = as.character(test_mx[,1])
test_mx = test_mx[,-1]
tmp_colnames = colnames(test_mx)
test_mx = as.matrix(test_mx)
rownames(test_mx) = tmp_rownames
colnames(test_mx) = tmp_colnames
test_mx
#               0           1            2          3
# a1 -0.079811371  0.82820704 -0.193860367 -1.1269632
# b1 -0.009402418 -1.19348155 -0.004519269  0.8921427
# c1 -0.784163111 -0.01340952  0.966208235  0.0135557

因为“reshape”已经定义了一个自定义的as.matrix方法,你实际上不需要这样做!

as.matrix(test_mx_cast)
#               0           1            2          3
# a1 -0.079811371  0.82820704 -0.193860367 -1.1269632
# b1 -0.009402418 -1.19348155 -0.004519269  0.8921427
# c1 -0.784163111 -0.01340952  0.966208235  0.0135557

但这仍然不能完全回答所有问题。为了进一步理解,现在比较两个矩阵:

> test_mx_cast_matrix <- as.matrix(test_mx_cast)
> class(test_mx)
[1] "cast_matrix" "matrix"     
> class(test_mx_cast_matrix)
[1] "cast_matrix" "matrix"     
> str(test_mx)
 num [1:3, 1:4] -0.0798 -0.0094 -0.7842 0.8282 -1.1935 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "a1" "b1" "c1"
  ..$ : chr [1:4] "0" "1" "2" "3"
> str(test_mx_cast_matrix)
 num [1:3, 1:4] -0.0798 -0.0094 -0.7842 0.8282 -1.1935 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "a1" "b1" "c1"
  ..$ : chr [1:4] "0" "1" "2" "3"
 - attr(*, "idvars")= chr "variable"
 - attr(*, "rdimnames")=List of 2
  ..$ :'data.frame':    3 obs. of  1 variable:
  .. ..$ variable: Factor w/ 3 levels "a1","b1","c1": 1 2 3
  ..$ :'data.frame':    4 obs. of  1 variable:
  .. ..$ t: int [1:4] 0 1 2 3

嗯。当我们as.matrix直接使用时,attributes“reshape”包添加的所有内容都被保留了,但是当我们手动进行处理时,它仍然声称是一样的class,但是所有的自定义attributes都被剥离了。

所以呢?

好吧,既然 R 认为那test_mx是 a cast_matrix,那么当你调用 时as.data.frame,它实际上调用的是as.data.frame.cast_matrix,而不是as.data.frame.matrix

看看如何as.data.frame.cast_matrix定义,这些attributes对于重新创建您的data.frame,因此是您的错误至关重要。以下是该函数的内容:

> as.data.frame.cast_matrix
function (x, row.names, optional, ...) 
{
    unx <- unclass(x)
    colnames(unx) <- rownames(rcolnames(x))
    r.df <- data.frame(rrownames(x), unx, check.names = FALSE)
    class(r.df) <- c("cast_df", "data.frame")
    attr(r.df, "idvars") <- attr(x, "idvars")
    attr(r.df, "rdimnames") <- attr(x, "rdimnames")
    rownames(r.df) <- 1:nrow(r.df)
    r.df
}
<environment: namespace:reshape>

所以,你现在有三个选择:

  1. 升级到“reshape2”——好建议,但请记住,仍有很多人没有费心进行转换。

  2. 正确使用“reshape”,这需要更多地查看它创建的对象的strclasses 和attributes。在这里“正确”使用它本来就是使用as.data.frame(test_mx_cast_matrix).

  3. 指定method你想要使用的(当你不知道包是否在重新定义方法时,这是非常安全的——通常,当它们创建新类时,你还应该检查是否已经创建了新方法)。相比:

    > as.data.frame(test_mx)        ## Calls `as.data.frame.cast_matrix` ERROR!
    Error in data.frame(rrownames(x), unx, check.names = FALSE) : 
      arguments imply differing number of rows: 0, 3
    > as.data.frame.matrix(test_mx) ## Specifies the `as.data.frame` method. WORKS!
                  0           1            2          3
    a1 -0.079811371  0.82820704 -0.193860367 -1.1269632
    b1 -0.009402418 -1.19348155 -0.004519269  0.8921427
    c1 -0.784163111 -0.01340952  0.966208235  0.0135557
    

叹。结束....

于 2013-07-26T05:36:08.697 回答
5

您应该使用reshape2, not reshape,因为后者已过时。

castdcast或改变acast

as.data.frame(test_mx)
            0           1            2           3
1 -0.08120468  0.97593052 -0.006127179 -1.15107784
2 -0.04165681 -1.02810193  0.004637454  0.99042403
3 -0.87862063  0.07346341  1.019113669 -0.01769976
于 2013-07-25T21:45:08.140 回答