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
array
s 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With