如何用 tidyr 替换数组的 reshape2::melt ?

ban*_*nbh 7 arrays r reshape2 tidyr

我想将矩阵/数组(带有暗名称)转换为数据框。使用 可以很容易地完成此操作reshape2::melt,但使用 似乎更困难tidyr,并且实际上在数组的情况下实际上不可能。我错过了什么吗?(特别是因为reshape2自称已退休;请参阅https://github.com/hadley/reshape)。

例如,给定以下矩阵

MyScores <- matrix(runif(2*3), nrow = 2, ncol = 3, 
                   dimnames = list(Month = month.name[1:2], Class = LETTERS[1:3]))
Run Code Online (Sandbox Code Playgroud)

我们可以将其转换为数据框,如下所示

reshape2::melt(MyScores, value.name = 'Score') # perfect
Run Code Online (Sandbox Code Playgroud)

或者,使用tidyr如下:

as_tibble(MyScores, rownames = 'Month') %>% 
  gather(Class, Score, -Month)
Run Code Online (Sandbox Code Playgroud)

在这种情况下reshape2tidyr看起来很相似(尽管reshape2如果您正在寻找长格式数据框,则更短)。

然而对于数组来说,这似乎更困难。给定

EverybodyScores <- array(runif(2*3*5), dim = c(2,3,5), 
                         dimnames = list(Month = month.name[1:2], Class = LETTERS[1:3], StudentID = 1:5))
Run Code Online (Sandbox Code Playgroud)

我们可以将其转换为数据框,如下所示:

reshape2::melt(EverybodyScores, value.name = 'Score') # perfect
Run Code Online (Sandbox Code Playgroud)

但使用tidyr它并不清楚如何做到这一点:

as_tibble(EverybodyScores, rownames = 'Month') # looses month information and need to distange Class and StudentID
Run Code Online (Sandbox Code Playgroud)

在这种情况下,正确的解决方案是坚持使用吗reshape2

Cal*_*You 2

我刚刚通过尝试发现的一种方法是强制通过tbl_cube. 我从来没有真正使用过这个类,但它似乎在这个例子中起到了作用。

EverybodyScores <- array(
  runif(2 * 3 * 5),
  dim = c(2, 3, 5),
  dimnames = list(Month = month.name[1:2], Class = LETTERS[1:3], StudentID = 1:5)
)
library(tidyverse)
library(cubelyr)
EverybodyScores %>%
  as.tbl_cube(met_name = "Score") %>%
  as_tibble
#> # A tibble: 30 x 4
#>    Month    Class StudentID Score
#>    <chr>    <chr>     <int> <dbl>
#>  1 January  A             1 0.366
#>  2 February A             1 0.254
#>  3 January  B             1 0.441
#>  4 February B             1 0.562
#>  5 January  C             1 0.313
#>  6 February C             1 0.192
#>  7 January  A             2 0.799
#>  8 February A             2 0.277
#>  9 January  B             2 0.631
#> 10 February B             2 0.101
#> # ... with 20 more rows
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.2.0) 于 2018-08-15 创建。

  • 我相信“as.tbl_cube”已从“dplyr”中移出并移至“cubelyr”中(请参阅https://rdrr.io/cran/cubelyr/man/as.tbl_cube.html)。 (2认同)