michael papenfus
2006-Jun-27 05:28 UTC
[R] Adding elements of matrices of different dimensions
If I have two matrices:> a<-matrix(1:5,ncol=1)[,1] [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5> b<-matrix(1:50,ncol=10)[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 6 11 16 21 26 31 36 41 46 [2,] 2 7 12 17 22 27 32 37 42 47 [3,] 3 8 13 18 23 28 33 38 43 48 [4,] 4 9 14 19 24 29 34 39 44 49 [5,] 5 10 15 20 25 30 35 40 45 50 How can I add a[1,1] to each column in the first row of b. and the then add a[2,1] to each column in second row of b and so on. I know there must be a way to use the apply function or nested for loops but I can't seem to get it working in R. thanks, michael [[alternative HTML version deleted]]
Dimitris Rizopoulos
2006-Jun-27 07:00 UTC
[R] Adding elements of matrices of different dimensions
try the following: matrix(1:50, ncol = 10) + 1:5 # or b + drop(a) I hope it helps. Best, Dimitris ---- Dimitris Rizopoulos Ph.D. Student Biostatistical Centre School of Public Health Catholic University of Leuven Address: Kapucijnenvoer 35, Leuven, Belgium Tel: +32/(0)16/336899 Fax: +32/(0)16/337015 Web: http://med.kuleuven.be/biostat/ http://www.student.kuleuven.be/~m0390867/dimitris.htm ----- Original Message ----- From: "michael papenfus" <papenfus at gmail.com> To: <r-help at stat.math.ethz.ch> Sent: Tuesday, June 27, 2006 7:28 AM Subject: [R] Adding elements of matrices of different dimensions> If I have two matrices: > >> a<-matrix(1:5,ncol=1) > > [,1] > [1,] 1 > [2,] 2 > [3,] 3 > [4,] 4 > [5,] 5 >> b<-matrix(1:50,ncol=10) > > [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] > [1,] 1 6 11 16 21 26 31 36 41 46 > [2,] 2 7 12 17 22 27 32 37 42 47 > [3,] 3 8 13 18 23 28 33 38 43 48 > [4,] 4 9 14 19 24 29 34 39 44 49 > [5,] 5 10 15 20 25 30 35 40 45 50 > > How can I add a[1,1] to each column in the first row of b. > and the then add a[2,1] to each column in second row of b > and so on. > > I know there must be a way to use the apply function or nested for > loops but > I can't seem to get it working in R. > thanks, > michael > > [[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 >Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm