[R] transformation matrice of vector into array
Tony Plate
tplate at acm.org
Thu Jul 27 16:59:44 CEST 2006
Here's a way to convert a matrix of vectors like you have into an array:
> x <- array(lapply(seq(0,len=6,by=4), "+", c(a=1,b=2,c=3,d=4)),
dim=c(2,3), dimnames=list(c("X","Y"),c("e","f","g")))
> x
e f g
X Numeric,4 Numeric,4 Numeric,4
Y Numeric,4 Numeric,4 Numeric,4
> x[["Y","e"]]
a b c d
5 6 7 8
> xa <- array(unlist(x, use.names=F), dim=c(length(x[[1,1]]),dim(x)),
dimnames=c(list(names(x[[1,1]])),dimnames(x)))
> x["Y","e"]
[[1]]
a b c d
5 6 7 8
> xa[,"Y","e"]
a b c d
5 6 7 8
>
Then you can do whatever sums you want over the array.
I have not extensively checked the above code, and if I were going to
use it, I would do numerous spot checks of elements to make sure all the
elements are going to the right places -- it's not too difficult to make
mistakes when pulling apart and reassembling arrays like this. (For
simpler cases involving lists of vectors or matrices, the abind()
function can help.)
-- Tony Plate
Jessica Gervais wrote:
> Hi,
>
> I need some help
>
> I have a matrix M(m,n) in which each element is a vector V of lenght 6
> 1 2 3 4 5 6 7
> 1 List,6 List,6 List,6 List,6 List,6 List,6 List,6
> 2 List,6 List,6 List,6 List,6 List,6 List,6 List,6
> 3 List,6 List,6 List,6 List,6 List,6 List,6 List,6
> 4 List,6 List,6 List,6 List,6 List,6 List,6 List,6
>
>
> i would like to make the sum on the matrix of each element of the
> matrix, that is to say
> sum(on the matrix)(M[j,][[j]][[1]])
> sum(on the matrix)(M[j,][[j]][[2]])
> ...
> sum(on the matrix)(M[j,][[j]][[6]])
>
> I don't really know how to do.
> I thought it was possible to transform the matrix M into an array A of
> dimension (m,n,6), and then use the command sum(colsums(A[,,1]), which
> seems to be possible and quite fast.
> ...but I don't know how to convert a matrix of vector into an array....
>
> As anyone any little idea about that ?
>
> Thanks by advance
>
> Jessica
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list