【问题标题】:Write a function that integrates another function in R在 R 中编写一个集成另一个函数的函数
【发布时间】:2021-08-17 09:43:57
【问题描述】:

我编写了这个有效的函数。 对于另一个功能,我需要集成这个。

    Shatc<-function(t){
  for (i in 1:n) {
  if(censoring$ctime[i]<t){
    d[i]<-sum(censoring$cens[1:i])
    num[i]<-n-(d[i]-1)
    sc[i]<-1-(d[i]/num[i])
  }
    else{
      break
    }
  }
  prod(sc)
}
> Shatc(0.2)
[1] 0.583874
> Shatc(0.4)
[1] 0.01419291

这是第二个功能

whatC<-function(t){
  integrate(Shatc,lower=0,upper=t)$value    
}

但是当我运行whatC时,会出现这个错误

Error in integrate(Shatc, lower = 0, upper = t) : 
  evaluation of function gave a result of wrong length
In addition: Warning messages:
1: In if (censoring$ctime[i] < t) { :
  the condition has length > 1 and only the first element will be used
2: In if (censoring$ctime[i] < t) { :
  the condition has length > 1 and only the first element will be used
3: In if (censoring$ctime[i] < t) { :
  the condition has length > 1 and only the first element will be used
4: In if (censoring$ctime[i] < t) { :
  the condition has length > 1 and only the first element will be used
5: In if (censoring$ctime[i] < t) { :
  the condition has length > 1 and only the first element will be used

【问题讨论】:

  • 您好,请与dput(head(data)) 分享您的数据的可重复样本,以便我们使用它,您将有更好的机会获得良好的相关回复。

标签: r function


【解决方案1】:

如果没有 censoringdnumsc,我将无法复制,但您似乎需要对 Shatc 进行矢量化。

integrate 将向它正在集成的函数发送一个数组,并且它需要一个数组输出。 Vectorize 函数应该可以工作:

whatC<-function(t){
  integrate(Vectorize(Shatc),lower=0,upper=t)$value    
}

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2020-10-11
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多