Melt equivalent in tidyverse for list of matrices

I have a list of matrices which I used to transform with replace2::melt(). Now that replace2 is retired, I'm trying to figure this out in tidyverse without much luck. I've tried as_tibble, flatten, unnest, but can't seem to find the right combination to generate the exact same output as melt().

Here's an example of what I mean.

a <- lapply(1:2,function(x) matrix(rnorm(4),nrow=2))

#this is what the list looks like
a
#> [[1]]
#>            [,1]       [,2]
#> [1,] -0.7685571  0.4816393
#> [2,]  1.1192629 -0.2190647
#> 
#> [[2]]
#>            [,1]        [,2]
#> [1,]  0.8859384 -0.34275513
#> [2,] -0.1185307 -0.02376784

#this is what it should transform to
reshape2::melt(a)
#>   Var1 Var2       value L1
#> 1    1    1 -0.76855707  1
#> 2    2    1  1.11926291  1
#> 3    1    2  0.48163934  1
#> 4    2    2 -0.21906466  1
#> 5    1    1  0.88593842  2
#> 6    2    1 -0.11853074  2
#> 7    1    2 -0.34275513  2
#> 8    2    2 -0.02376784  2

Created on 2020-03-04 by the reprex package (v0.3.0)

You may well have seen this already, but here are a couple of options on SO:

I think you will need to name the matrix rows and columns first.

1 Like

Thanks. I had seen that post, but looking at it again gave me an idea to solve the problem. I turned the list of matrices into an array and used the code below, which worked.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

b <- replicate(2, matrix(rnorm(4),nrow=2))
dimnames(b) <- list(number=1:2,row=1:2,column=1:2)

b_trans <- b %>%  
  as.tbl_cube(met_name = "value") %>%
  as_tibble()

b_trans
#> # A tibble: 8 x 4
#>   number   row column    value
#>    <int> <int>  <int>    <dbl>
#> 1      1     1      1 -1.43   
#> 2      2     1      1 -0.104  
#> 3      1     2      1 -0.0509 
#> 4      2     2      1  1.46   
#> 5      1     1      2 -0.0241 
#> 6      2     1      2  0.00820
#> 7      1     2      2 -0.672  
#> 8      2     2      2  1.10

Created on 2020-03-04 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.