Convert 3D array to tidy data frame?

Viewed 113

I have a 3D array that looks like this:

# Create two vectors 
vector1 <- c(1,2,3,4,5,6)
vector2 <- c(10, 11, 12, 13, 14, 15,16)

# Convert to 3D array
my_array <- array(c(vector1, vector2), dim = c(2,3,2))
print(my_array)

where the output is

, , 1

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

, , 2

     [,1] [,2] [,3]
[1,]   10   12   14
[2,]   11   13   15

I would like to turn this into a tidy dataset, where is one row per value, and there are 4 columns for each of the values:

  • the value itself
  • dimension 1
  • dimension 2
  • dimension 3

so for example, a few rows would be

Value Dimension1(Row) Dimension2(Column) Dimension3(Width)
1     1               1                  1
2     2               1                  1
...
15    2               3                  2

Is there a good way to do this in base R, or with tidyverse tools like tidyr?

1 Answers

We could use reshape2::melt

library(reshape2)
melt(my_array)

-output

 Var1 Var2 Var3 value
1     1    1    1     1
2     2    1    1     2
3     1    2    1     3
4     2    2    1     4
5     1    3    1     5
6     2    3    1     6
7     1    1    2    10
8     2    1    2    11
9     1    2    2    12
10    2    2    2    13
11    1    3    2    14
12    2    3    2    15

Or use as.data.frame.table in base R

as.data.frame.table(my_array)

Or may also use

cbind(which(is.finite(my_array), arr.ind = TRUE), value = c(my_array))
Related