Ben Ben - 3 years ago 174
R Question

Reducing a 3d array to 2d

Is there a more succinct, one-liner way to do the following?

x <- array(1:12, dim = c(3, 2, 2))

> x[1,,]
[,1] [,2]
[1,] 1 7
[2,] 4 10

> x[2,,]
[,1] [,2]
[1,] 2 8
[2,] 5 11

> x[3,,]
[,1] [,2]
[1,] 3 9
[2,] 6 12

# Reduce 3d array to 2d (Is there a more elegant way?)
y <- x
dim(y) <- c(nrow(y), 4)


> y
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12

Answer Source

You can just feed your original array to the array constructor again, and use dim to get the dimension you want to preserve:

y <- array(x, dim = c(dim(x)[1], 4))

     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

If you wanted a version that doesn't rely on hardcoding the number of columns:

y <- array(x, dim = c(dim(x)[1], dim(x)[2] * dim(x)[3]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download