Varren - 20 days ago 4x

R Question

I want to produce all possible

`w`

`s`

`w_min`

`w_max`

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

result = c()

for (i in 1:20) {

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

## what do I need to do here??

}

result

Answer

**You want a matrix, where you have many columns while each column is a vector**.

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 = 1)`

with step `1`

.

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]
#[1,] 4 3 2 1 0
#[2,] 5 4 3 2 1
#[3,] 6 5 4 3 2
#[4,] 7 6 5 4 3
#[5,] 8 7 6 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]
#[1,] 4 3 2 1 0
#[2,] 5 4 3 2 1
#[3,] 6 5 4 3 2
#[4,] 7 6 5 4 3
#[5,] 8 7 6 5 4
```

**Apart from a matrix, you can also store your result in a list of vectors.**

```
w <- vector("list", length(s)) ## set up a `length(s)` list
for (i in 1:length(s)) {
## fill i-th element of the list; note the `[[i]]`
w[[i]] <- s[i] * w_min + (1 - s[i]) * w_max
}
w
#[[1]]
#[1] 4 5 6 7 8
#
#[[2]]
#[1] 3 4 5 6 7
#
#[[3]]
#[1] 2 3 4 5 6
#
#[[4]]
#[1] 1 2 3 4 5
#
#[[5]]
#[1] 0 1 2 3 4
```

But there is no real vectorization approach here. We can at most hide the loop by an `lapply`

:

```
w <- lapply(s, function (x) x * w_min + (1 - x) * w_max)
w
#[[1]]
#[1] 4 5 6 7 8
#
#[[2]]
#[1] 3 4 5 6 7
#
#[[3]]
#[1] 2 3 4 5 6
#
#[[4]]
#[1] 1 2 3 4 5
#
#[[5]]
#[1] 0 1 2 3 4
```

Source (Stackoverflow)

Comments