【问题标题】:How to run a function (passing vectors that stay the same & vector that changes in each iteration) without using a for loop?如何在不使用 for 循环的情况下运行函数(传递保持不变的向量和在每次迭代中变化的向量)?
【发布时间】: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 的向量。非常感谢任何帮助!

标签: r for-loop lapply


【解决方案1】:

原来是lappy的一个应用。

vol_new = lapply(adnew, function(x) {return((x/ad)*vol)})

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 2018-05-23
    • 2022-01-23
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多