Araen - 3 months ago 16

R Question

I have a matrix with 2 columns, and I'd like to turn it into a matrix with specified dimensions.

`> t <- matrix(rnorm(20), ncol=2, nrow=10)`

[,1] [,2]

[1,] 1.4938530 1.2493088

[2,] -0.8079445 1.8715868

[3,] 0.5775695 -0.9277420

[4,] 0.4415969 2.6357908

[5,] 0.3209226 -1.1306049

[6,] 0.5109251 -0.8661100

[7,] 1.9495571 0.2092941

[8,] 0.7816373 1.1517466

[9,] 0.0300595 -0.1351532

[10,] 0.7550894 0.7778869

What I'd like to do is something like:

`> tt <- matrix(t, ncol=4, nrow=5)`

[,1] [,2] [3,] [4,]

[1,] 1.4938530 1.2493088 -0.8079445 1.8715868

[2,] 0.5775695 -0.9277420 0.4415969 2.6357908

[3,] etc.

I tried to do things with modulo but my head hurts too much for me to try even one more minute.

Answer

You can transpose your first matrix, so that data is stored in the order you want, and then fill the second matrix by row:

```
tt <- matrix(t(t), ncol=4, nrow=5, byrow = T)
t
# [,1] [,2]
# [1,] -1.4162465950 0.01532476
# [2,] -0.2366332875 -0.04024386
# [3,] 0.5146631983 -0.34720239
# [4,] 1.9243922633 -0.24016160
# [5,] 1.6161165230 0.63187438
# [6,] -0.3558181508 -0.73199138
# [7,] 0.7459405376 0.01934826
# [8,] -1.0428581093 -2.04422042
# [9,] 0.0003166344 0.98973993
#[10,] 0.6390745275 -0.65584930
tt
# [,1] [,2] [,3] [,4]
# [1,] -1.4162465950 0.01532476 -0.2366333 -0.04024386
# [2,] 0.5146631983 -0.34720239 1.9243923 -0.24016160
# [3,] 1.6161165230 0.63187438 -0.3558182 -0.73199138
# [4,] 0.7459405376 0.01934826 -1.0428581 -2.04422042
# [5,] 0.0003166344 0.98973993 0.6390745 -0.65584930
```

When you work with matrix in R, you can think of it as a vector with data stored column by column. So extracting data by row from a matrix is not as straight forward as extracting by column which is essentially how data is stored. After transposing the first matrix, the data will be stored in an order you want to extract and then fill the second matrix by row would be straight forward.