[R] abind

Tony Plate tplate at acm.org
Tue Oct 28 18:55:03 CET 2008


It looks like you are trying to construct a ragged array, where the extent of the dimensions varies.

However, in R, ordinary arrays have a regular structure, e.g., the rows of a matrix always have the same number of columns.  This is the kind of object abind() constructs.

So, to bind your two matrices together, abind() requires that their dimensions match

> a <- matrix(1:6, ncol=3, byrow=T)
> b <- matrix(7:10, ncol=2, byrow=T)
> a
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
> b
     [,1] [,2]
[1,]    7    8
[2,]    9   10
> library(abind)
> abind(a, b, along=3)
Error in abind(a, b, along = 3) : 
  arg 'X2' has dims=2, 2, 1; but need dims=2, 3, X

The only way to get abind to bind these together on the third dimension is to pad out the smaller matrix with NA's, e.g.:

> abind(a, cbind(b, NA), along=3)
, , 1

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

, , 2

     [,1] [,2] [,3]
[1,]    7    8   NA
[2,]    9   10   NA

> 

('a' and 'b' do match on the number of rows, so you can bind them together as columns as does cbind(), e.g.:
> abind(a, b, along=2)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    7    8
[2,]    4    5    6    9   10
>
)


If none of this is what you want, you could consider storing the matrices in a list, as another poster suggested.

-- Tony Plate


Suyan Tian wrote:
> I am trying to combine two arrays with different dimensions into one. 
> For example
> 
> The first one is
> 1  2  3
> 4  5  6
> 
> The second one is
> 7 8
> 9 10
> 
> The resulted one would be like
> , , 1
> 1 2 3
> 4 5 6
> , , 2
> 7 8
> 9 10
> 
> I used abind to do this, but failed. Could somebody please let me know 
> how to do this in R? Thanks so many.
> 
> 
> Suyan
> 
> ______________________________________________
> R-help at r-project.org 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