s-news
[Top] [All Lists]

Re: simple array arithmetic

To: Jean V Adams <jvadams@usgs.gov>
Subject: Re: simple array arithmetic
From: Patrick Burns <pburns@pburns.seanet.com>
Date: Fri, 14 May 2004 20:51:17 +0100
Cc: s-news@wubios.wustl.edu
References: <OFEF8C4B5D.88548B4F-ON85256E94.00672082@er.usgs.gov>
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.0.1) Gecko/20020823 Netscape/7.0
You have an easy case, where you can just say:

a + 10 * as.vector(b)

In general, you want to use "sweep".  For example

sweep(a, 1:2, 10 * b, "+")

for your problem.

Or

d <- matrix(1:8, 4, 2)
sweep(a, 2:3, 10 * d, "+")


Patrick Burns

Burns Statistics
patrick@burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Jean V Adams wrote:

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



--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu.  To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message:  unsubscribe s-news






<Prev in Thread] Current Thread [Next in Thread>