R 中的 If 语句和Integrate()函数

问题描述 投票:0回答:1

if 语句不适用于积分吗?我必须做一些比这更复杂的事情,但我提供这个例子是因为它隔离了问题。

Kernel = function(x){
  if(abs(x)<1){
    w = 1 - abs(x)
  } else{
    w = 0 
  }
  return(w)
}


integrate(Kernel, 
          0, 
          1)

错误信息:

条件长度> 1并且仅使用第一个元素

r if-statement numerical-integration
1个回答
1
投票
Kernel = function(x){
  pmax(1-abs(x), 0)
}


integrate(Kernel, 0, 1)
0.5 with absolute error < 5.6e-15

甚至:

Kernel1 = function(x){
  ifelse(abs(x)<1,  1-abs(x), 0)
}


integrate(Kernel1, 0, 1)
0.5 with absolute error < 5.6e-15

如果您想保持编写函数的方式,则必须对其进行矢量化:

Kernel2 = function(x){
  ifelse(abs(x)< 1, 1-abs(x), 0)
  if(abs(x)<1){
    w = 1 - abs(x)
  } else{
    w = 0 
  }
  return(w)
}


integrate(Vectorize(Kernel2), 0, 1)
0.5 with absolute error < 5.6e-15
© www.soinside.com 2019 - 2024. All rights reserved.