您需要一个矩阵,其中有很多列,而每列都是一个向量。
为了提供一个玩具示例,我需要让你的 "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