Varren - 5 months ago 18

R Question

trying to figure out how to program this in the best way..

I want to produce all possible

`w`

`s`

`w_min`

`w_max`

`s <- seq(-2, 2, by=0.1)`

t = c()

for (i in 1:20){

w = s[i]*w_min+(1-s[i])*w_max

}

t

Answer

**You want a matrix.** In order to provide a toy example, I need to make your *" w_min and w_max are 5 * 1 vectors"* concrete:

```
## note, they are just plain vectors without dimension
## if you have a `5 * 1` matrix, use `c(w_min)` and `c(w_max)` to drop dimension
w_min <- 1:5
w_max <- 2:6
```

Also, to make the example small, I will consider `s <- seq(-2, 2, by = 0.5)`

with step `0.5`

.

First, consider the loop-based method:

```
w <- matrix(0, 5, length(s)) ## set up a `5 * length(s)` matrix
for (i in 1:length(s)) {
## fill i-th column of the matrix
w[, i] <- s[i] * w_min + (1 - s[i]) * w_max
}
w
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#[1,] 4 3.5 3 2.5 2 1.5 1 0.5 0
#[2,] 5 4.5 4 3.5 3 2.5 2 1.5 1
#[3,] 6 5.5 5 4.5 4 3.5 3 2.5 2
#[4,] 7 6.5 6 5.5 5 4.5 4 3.5 3
#[5,] 8 7.5 7 6.5 6 5.5 5 4.5 4
```

Then, the vectorized method:

```
## read `?outer`; the default function to apply is `FUN = "*"` for multiplication
w <- outer(w_min, s) + outer(w_max, 1 - s)
w
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#[1,] 4 3.5 3 2.5 2 1.5 1 0.5 0
#[2,] 5 4.5 4 3.5 3 2.5 2 1.5 1
#[3,] 6 5.5 5 4.5 4 3.5 3 2.5 2
#[4,] 7 6.5 6 5.5 5 4.5 4 3.5 3
#[5,] 8 7.5 7 6.5 6 5.5 5 4.5 4
```