[R] Stacking matrix columns
@vi@e@gross m@iii@g oii gm@ii@com
@vi@e@gross m@iii@g oii gm@ii@com
Sun Aug 6 19:36:01 CEST 2023
Based on a private communication, it sounds like Steven is asking the question again because he wants a different solution that may be the way this might be done in another language. I think he wants to use loops explicitly and I suspect this may be along the lines of a homework problem for him.
R has loops and if you loop over some variable moving "col" from 1 to the number of columns, then if your matrix is called "mat" you can use mat[,col] to grab a whole column at a time and concatenate the results gradually into one longer vector.
If you want a more loopy solution, simply reserve a vector big enough to hold an M by N matric (size is M*N) and loop over both "row" and "col" and keep adding mat[row,col] to your growing vector.
As stated, this is not the way many people think in R, especially those of us who know a matrix is just a vector with a bonus.
-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Steven Yen
Sent: Saturday, August 5, 2023 8:08 PM
To: R-help Mailing List <r-help using r-project.org>
Subject: [R] Stacking matrix columns
I wish to stack columns of a matrix into one column. The following
matrix command does it. Any other ways? Thanks.
> x<-matrix(1:20,5,4)
> x
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
> matrix(x,ncol=1)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
[11,] 11
[12,] 12
[13,] 13
[14,] 14
[15,] 15
[16,] 16
[17,] 17
[18,] 18
[19,] 19
[20,] 20
>
______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list