[R] is there a way to let R do smart matrix-vector operation
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Tue Mar 7 09:34:10 CET 2006
On 06-Mar-06 Michael wrote:
> Hi all,
>
> I want to substract vector B from A's each column... how can R do that
> smartly without a loop?
>
>> A=matrix(c(2:7), 2, 3)
>> A
> [,1] [,2] [,3]
> [1,] 2 4 6
> [2,] 3 5 7
>> B=matrix(c(1, 2), 2, 1)
>> B
> [,1]
> [1,] 1
> [2,] 2
>> A-B
> Error in A - B : non-conformable arrays
What a lot of answers to this query!
Also this one (which I adopted following someone's useful
response to a query of mine a very long time ago -- sorry
I can't now trace who it was):
## Binary operators %+.%, %.+% to add vector
## or kx1 or 1xk matrix to cols or rows of a matrix
"%+.%"<-function(X,x){sweep(X,1,x,"+")} ## Adds to cols
"%.+%"<-function(X,x){sweep(X,2,x,"+")} ## Adds to rows
So A %+.% x would add the elements of x to cols of A,
or A %.+% y would add the elements of y to rows of A,
provided the length of x is the number of rows in A
or the length or y is the number of columns.
These operators can easily be extended to %-.%, %.-%,
%*.%, %.*%, %/.%, %./% (in an obvious notation).
I have the above operators set up in my .Rprofile (from
which the above code is copied). The only thing wrong with
them is that they are traps for typophiliacs (like me ... ).
Best wishes to all,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 07-Mar-06 Time: 08:34:03
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list