简体   繁体   English

如何在R中为integrate()做for循环

[英]how to do the for-loop for integrate() in R

The following is my R-code, if i set the "c" equals to 10,11,12,13,14 separately,to get five different "final",how could I set the loop for integrate()function?以下是我的 R 代码,如果我将“c”分别设置为 10、11、12、13、14,以获得五个不同的“最终”,我该如何设置集成()函数的循环? Thanks you in advance.提前谢谢你。

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

You can solve this by using anonymous functions and sapply您可以通过使用匿名函数和sapply来解决这个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})

Edit编辑

Onyambu found a better answer in the comments below Onyambu 在下面的评论中找到了更好的答案

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

I guess my answer is right.我想我的答案是对的。 May I post my own answer?我可以发布我自己的答案吗?

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM