is this the most straightforward way to convert an array into a data.table?
require(data.table)
require(ggplot2)
# this returns a data.table with both array's dimensions and values
aaa <- array(rnorm(3*4*2), dim = c(3,4,2))
DT1 <- as.data.table(as.data.frame.table(aaa))
# the following does not work properly, because it only returns the array values
DT2 <- as.data.table(aaa)
# plot values aggregated by 3rd array dim
ggplot(DT1, aes(Var1, Freq, fill = Var3)) + geom_boxplot()
# sum values by 2nd array dim
DT1[ , sum(Freq), Var2]
EDIT1: sorry, with "properly" I mean that I get a data frame with one column only, so that I don't know from which position in the original array a values has originated. The idea is to transform the array into a flat table, so that is easier to e.g. plot the variables using the dimensions as factors, or to aggregate values by factors. Would that be still possible with DT2?
EDIT2: one other useful thing would be to convert the data.table back into the original array. Do you know a function that coerces data.table to array, by defining which columns to use as dimensions?
aaa <- array(rnorm(3*4*2), dim = c(3,4,2), list(Var1 = LETTERS[1:3], Var2 = LETTERS[1:4], Var3 = LETTERS[1:2] ))
DT1 <- setDT(melt(aaa))
# convert DT1 back to aaa
array(data = DT1[ ,value],
dim = c(length(unique(DT1[ ,Var1])),
length(unique(DT1[ ,Var2])),
length(unique(DT1[ ,Var3]))),
dimnames = list(Var1 = unique(DT1[ ,Var1]),
Var2 = unique(DT1[ ,Var2]),
Var3 = unique(DT1[ ,Var3])))
thanks!