[R] is there a way to let R do smart matrix-vector operation?

Berton Gunter gunter.berton at gene.com
Tue Mar 7 00:24:29 CET 2006


Well, I'm not sure what's "smart" and what's "dumb." As Mark said, a
standard prescription for this sort of thing is to use apply() type calls --
but that actually is still using a loop, though generally very efficiently. 

If you want to avoid even that sort of hidden looping then try:


matrix(as.vector(A)-as.vector(B),nr=nrow(A))

If B is a vector, not a matrix, the as.vector(B) cast isn't necessary.


-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Michael
> Sent: Monday, March 06, 2006 3:11 PM
> To: R-help at stat.math.ethz.ch
> Subject: [R] is there a way to let R do smart matrix-vector operation?
> 
> 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
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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
>




More information about the R-help mailing list