写一个函数,它集成了r中的另一个函数



我写的这个函数是有效的。对于另一个函数,我需要对这个积分。

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

没有censoring,d,numsc我无法复制,但看起来您需要对Shatc进行矢量化。

integrate将发送一个数组给它正在积分的函数,并且它期望一个数组输出。Vectorize函数应该工作:

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

最新更新