[R] adding a row to a matrix

Christos Hatzis christos at silicoinsights.com
Sun Apr 9 17:40:56 CEST 2006


You can try sweep:

sweep(a,2,b,"+") 

-Christos

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Tim Smith
Sent: Sunday, April 09, 2006 11:28 AM
To: r-help at stat.math.ethz.ch
Subject: [R] adding a row to a matrix

Hi All,
  This is probably a very simple question. I was trying to add a row to the
rows in a matrix. For example:
   
  > a <- matrix(1:6,2,3)
> 
> b <- a[1,]
> 
> print(a)
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> 
> print(b)
[1] 1 3 5
   
  I now want to add 'b' to every row of 'a', so the end result should look
like:
       [,1] [,2] [,3]
[1,]    2    6   10
[2,]    3    7   11
   
  But if I do c = apply(a,1,"+",b), I get:
  > c
     [,1] [,2]
[1,]    2    3
[2,]    6    7
[3,]   10   11
  Now, I could easily transform this to get what I want, but I'd like to
know how I could get the result without many intermediate steps ( I have
large matrices, so transforming them at each step would not be efficient).
   
  If someone could point me in the right direction, that would be a great
help.
   
  thanks.
   
   
   

			
---------------------------------

	[[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