Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert 3 dimensional array into dataframe

I need to convert a 3 dimensional array into a data.frame.

Example:

#create fake data
#two vectors 
vec1 = c(2,13,22,98,4,8,8,1,10)
vec2 = c(2,4,6,7,1,55,32,12,1)

#3 dim array
result = array(c(vec1,vec2),dim = c(3,3,2))
print(result)

, , 1

     [,1] [,2] [,3]
[1,]    2   98    8
[2,]   13    4    1
[3,]   22    8   10

, , 2

     [,1] [,2] [,3]
[1,]    2    7   32
[2,]    4    1   12
[3,]    6   55    1

How can I get the following 9 col data.frame, where letters are colnames (it could be also default values..) and each row represents the result[,,i] slice:

a   b   c   d  e  f  g  h   i
2  13  22  98  4  8  8  1  10
2   4   6   7  1  55 32 12  1

my real array dim = 140, 200, 20000

thanks

like image 802
aaaaa Avatar asked Nov 19 '17 21:11

aaaaa


Video Answer


2 Answers

arrays and matrices are vectors with dimensions, so recast to a matrix, then data.frame:

data.frame(matrix(result, nrow=2, byrow=TRUE))
# generalisably:
data.frame(matrix(result, nrow=dim(result)[3], byrow=TRUE))

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  2 13 22 98  4  8  8  1 10
#2  2  4  6  7  1 55 32 12  1
like image 97
thelatemail Avatar answered Sep 30 '22 09:09

thelatemail


You could try mapply:

as.data.frame(mapply(function(x, y) c(x, y), result[,,1], result[,,2]))
#  V1 V2 V3 V4 V5 V6 V7 V8 V9
#1  2 13 22 98  4  8  8  1 10
#2  2  4  6  7  1 55 32 12  1
like image 23
LyzandeR Avatar answered Sep 30 '22 09:09

LyzandeR