【问题标题】:how to do the for-loop for integrate() in R如何在R中为integrate()做for循环
【发布时间】:2020-05-26 10:13:22
【问题描述】:

以下是我的 R 代码,如果我将“c”分别设置为 10、11、12、13、14,以获得五个不同的“最终”,我该如何设置积分()函数的循环?提前谢谢你。

a<-1;b<-2;c<-10
integrand<-function(k) 
{
  a+b*c*k
}
outcome<-integrate(integrand, lower = 0, upper = 1)
final<-outcome$value+c

【问题讨论】:

    标签: r for-loop integrate


    【解决方案1】:

    你可以通过使用匿名函数和sapply来解决这个问题

    # create a function with two parameters
    aux_function<-function(k,c) 
    {
      a+b*c*k
    }
    # integrate on x with different c values
    outcome<-sapply(10:14, function(c) {integrate(function(x) {aux_function(x,c)}, lower = 0, upper = 1)$value +c})
    

    编辑

    Onyambu 在下面的 cmets 中找到了更好的答案

    outcome<-sapply(10:14,  function(c) {integrate(aux_function,lower=0,upper=1,c=c)$value +c})
    

    【讨论】:

    • function(x) 的目的是什么?还要避免给出与 OP 给出的名称不同的名称sapply(10:14, function(c) integrate(integrand,lower=0,upper=1,c=c)$value+c)
    • @Onyambu 运行您的代码时出现此错误Error in f(x, ...) : unused argument (c = c)
    • 这里的integrand 与您的aux_function 完全相同。不是提供的一个 OP
    • 哦,好的,我现在明白了,你说得对,这比我的解决方案更容易阅读
    【解决方案2】:

    我想我的答案是对的。我可以发布我自己的答案吗?

      h<- list()
      g<- numeric()
      a<-1;b<-2;c<-c(10,11,12,13,14)
    
      for(i in 1:length(c))
      {
        h[[i]] = function(k){ a+b*c[i]*k}
        g[i] = integrate(h[[i]], lower=0, upper=1)$value+c[i]
      }
      g
    

    【讨论】:

    • 如果您希望 c 成为不同长度的向量并且不想每次都更新循环,您可能会从使用 for(i in 1:length(c)) 中受益。
    • 是的,您可以回答自己的问题,请参阅here 和here。
    猜你喜欢
    • 2020-01-04
    • 2019-08-25
    • 2014-11-01
    • 1970-01-01
    • 2011-03-20
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多