Question

I've got a 3-dimensional array in R that I can use melt() on to produce a long data.frame:

library(abind)
library(reshape2)
a = matrix(1:4, nrow=2, ncol=2)
x = abind(a, a, along=3)
y = melt(x)
y

which yields:

  Var1 Var2 Var3 value
1    1    1    1     1
2    2    1    1     2
3    1    2    1     3
4    2    2    1     4
5    1    1    2     1
6    2    1    2     2
7    1    2    2     3
8    2    2    2     4

How can I transform the data back to the original array? It should work with acast, but I can't find the right arguments for it:

y['idx'] = rownames(y)
acast(y, idx~Var1+Var2+Var3, value.var='value') # does not work this way
Was it helpful?

Solution

For multiple dimensions, you need some more tildes (if I understood your question correctly):

acast(y, Var1 ~ Var2 ~ Var3)
# , , 1
# 
#   1 2
# 1 1 3
# 2 2 4
# 
# , , 2
# 
#   1 2
# 1 1 3
# 2 2 4

To generalize this behavior, you can try constructing a formula with paste:

Form <- as.formula(paste(grep("^Var", names(y), value=TRUE), 
                         collapse = " ~ "))
acast(y, Form)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top