【发布时间】:2021-09-30 14:10:32
【问题描述】:
我需要运行一个函数固定的次数。
在每个步骤中:
- “vol”和“ad”保持不变。
- 'adnew' 的计算方法是将 'vol'(其 f = 1)的元素替换为 'step'
最终输出:'vol_new' - 包含 11 个元素的矩阵或列表,每个元素由一个长度为 5 的向量组成。
感谢您的帮助!
示例代码
vol <- c(15, 10, 25, 40, 45)
ad <- c(100, 200, 300, 150, 250)
# filter - stays the same
f <- c( 1, 1, 1, 0, 0)
# need to loop it 10 times (looping through 'step')
step = seq(0, 500, by = 50)
# for each 'step', adnew is calculated by replacing element of vol (whose f = 1) with 'step'
adnew <- rep(list(ad), length(step))
for (i in 1:length(step)) {
adnew[[i]][f==1] <- step[i]
}
# for each step, calculate the function 'calc'
Calc <- function(vol, ad, adnew) {
return((adnew/ad)*vol)
}
# desired output:
vol_new -- a matrix or list with 11 elements (corresponds to number of iterations), each element consisting of a vector of size 5.
【问题讨论】:
-
Calc 将为每一步返回一个向量。我不确定我是否理解它的输出如何进入
vol_new。你能用语言解释一下这其中的逻辑吗?这可能比它必须要复杂得多 -
你是对的。 Volnew 将是一个大小为 11(迭代次数)的矩阵或列表,每个都有一个大小为 5 的向量。非常感谢任何帮助!