你想要一個矩陣,你有很多列,而每列是一個向量。
提供這樣一種玩具的例子,我需要讓你的「w_min
和w_max
是5個* 1個向量」具體:
## 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
此外,爲了讓這個例子小,我會考慮s <- seq(-2, 2, by = 1)
與步驟1
。
首先,考慮基於循環的方法:
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
然後,量化方法:
## 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
從矩陣除此之外,您還可以將結果保存在一個載體列表。
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
但是這裏沒有真正的矢量化方法。我們至多可以通過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