rxk011 - 6 months ago 41

R Question

I have solution matrix(say A) to the indefinite equation x1+x2+x3+x4 = 6. Also, I have another matrix(say B) with columns are

`0 1 0 1`

0 0 1 1

I want to generate matrices using rows of A and the columns of B.

For an example, let (2,0,1,3) is the one solution(one row) of the matrix A. Then, the columns of my new matrix are

`0 0 0 1 1 1`

0 0 1 1 1 1

Columns of this new matrix are the multiples of columns of B. i.e., first column 2-times, third column 1-time and fourth column 3-times. I want to use this procedure all the rows of matrix A.

Answer

use `rep`

:

```
b <- matrix(c(0, 0, 1, 0, 0, 1, 1, 1), nrow = 2)
a <- c(2, 0, 1, 3)
b[, rep(1:ncol(b), a)]
```

if a has many rows:

```
lapply(1:nrow(a), function(i) b[, rep(1:ncol(b), a[i, ])])
```