is this the most straightforward way to convert an array into a data.table?
require(data.table)
require(ggplot2)
# this returns a data.tabl
depening on your desired output (since you are tryning to convert multiple dimension into a 'flat' table), here is a possible solution using the plyr-package:
plyr's adply takes a array, and retuns a data.frame that you can easily convert to a data.table
library(plyr)
dt <- setDT( adply( aaa, c(1,2) ) )
X1 X2 V1 V2
1: 1 1 -0.5869804 1.30996405
2: 2 1 1.3398003 1.87641841
3: 3 1 -0.3268114 -0.12771971
4: 1 2 0.8966523 -1.38669407
5: 2 2 -0.4612773 -1.48036434
6: 3 2 -0.6798351 -0.09369933
7: 1 3 0.1311092 0.40458169
8: 2 3 -1.7098850 0.39616792
9: 3 3 -0.4589561 -1.14020015
10: 1 4 0.5348955 -0.25779528
11: 2 4 0.7099319 0.19067120
12: 3 4 -0.1545822 -0.75378610
convert the data.table back into the original array
Here a quick and dirty solution
DT2 = as.data.table(aaa)
aaa2= array(dim = dim(aaa))
invisible(DT2[, aaa2[V1, V2, V3] <<- value, .(V1,V2,V3)])
all.equal(aaa,aaa2) # TRUE
only works for versions 1.11.4 and 1.11.2 but not for some earlier versions
both approaches essentially return the same data.table but with A=1
, B=2
, C=3
in your second approach, and rows ordered in different ways. so the second approach is the way to go.
DT2 <- as.data.table(aaa)
head(DT2)
# V1 V2 V3 value
#1: 1 1 1 0.32337516
#2: 1 1 2 1.59189589
#3: 1 2 1 -1.48751756
#4: 1 2 2 -0.86749305
#5: 1 3 1 0.01017255
#6: 1 3 2 2.66571093
#compare
DT[order(Freq), ]
#and
DT2[order(value), ]