I can't seem to figure out how to do a simple arithmetic operation with an
array and a matrix. I want to add a matrix to each "matrix part" of an
array, and get a result with the same structure as the array.
Here's an example:
a <- array(1:24, dim=c(3, 4, 2))
b <- matrix(1:12, nrow=3)
a
, , 1
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
, , 2
[,1] [,2] [,3] [,4]
[1,] 13 16 19 22
[2,] 14 17 20 23
[3,] 15 18 21 24
b
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> >
What I want to end up with is
, , 1
[,1] [,2] [,3] [,4]
[1,] 11 44 77 110
[2,] 22 55 88 121
[3,] 33 66 99 132
, , 2
[,1] [,2] [,3] [,4]
[1,] 23 56 19 122
[2,] 34 67 100 133
[3,] 45 78 111 144
But, when I try what seems to me to be the obvious approach,
apply(a, 3, "+", 10*b)
I get this:
[,1] [,2]
[1,] 11 23
[2,] 22 34
[3,] 33 45
[4,] 44 56
[5,] 55 67
[6,] 66 78
[7,] 77 89
[8,] 88 100
[9,] 99 111
[10,] 110 122
[11,] 121 133
[12,] 132 144
I can't figure out why the matrix structure (the dimensionality) wasn't
kept. I'd appreciate someone setting me straight.
JVA
`·.,, ><(((º> `·.,, ><(((º> `·.,, ><(((º>
Jean V. Adams
Statistician
U.S. Geological Survey
Great Lakes Science Center
c/o Marquette Biological Station
1924 Industrial Parkway
Marquette, MI 49855 U.S.A.
phone: (906) 226-1212
FAX: 906-226-3632
web site: www.glsc.usgs.gov
e-mail: JVAdams@usgs.gov
|