Shmoose - 8 months ago 42

R Question

I've been digging around the site for an answer to my question, and I'm new with R so I'm hoping this is even possible. I have two large matrices of simulations (A = 100,000 x 50 and B = 10,000 x 50) that I would like to randomly multiply element-wise by row.

Essentially I would like each row in A to randomly select a row from B for element-wise multiplication.

A:

`[,1] [,2] [,3] [,4] [,5]`

[1,] 1 1 1 1 1

[2,] 1 1 1 1 1

[3,] 1 1 1 1 1

[4,] 1 1 1 1 1

[5,] 1 1 1 1 1

[6,] 1 1 1 1 1

[7,] 1 1 1 1 1

[8,] 1 1 1 1 1

[9,] 1 1 1 1 1

[10,] 1 1 1 1 1

And

B:

`[,1] [,2] [,3] [,4] [,5]`

[1,] 1 1 1 1 1

[2,] 2 2 2 2 2

[3,] 3 3 3 3 3

[4,] 4 4 4 4 4

[5,] 5 5 5 5 5

Is there an operator that could go through A's rows and randomly select a row from B to pair for element wise multiplication? For results something like this:

`C <- A&*&B`

C

A[1,]*B[3,]

A[2,]*B[1,]

A[3,]*B[2,]

A[4,]*B[5,]

A[5,]*B[3,]

A[6,]*B[4,]

A[7,]*B[1,]

A[8,]*B[5,]

A[9,]*B[2,]

A[10,]*B[2,]

Thanks!

Answer Source

Try this:

```
row_id <- sample(1:nrow(B), nrow(A), replace = TRUE)
A * B[row_id, ]
```

I think I only need to explain what `sample()`

does. Consider:

```
sample(1:5, 10, replace = TRUE)
[1] 4 5 2 4 1 2 2 1 2 5
```

I did not set random seed by `set.seed()`

, so when you run it, you will get different result. But all you need to know is that: it is random.