我正在寫下面的函數,它應該計算seed.times處強度函數的值。使用While循環重寫用戶定義的函數
Intensity=function(params, eval.times, event.times) {
# This function computes the value of the intensity function.
# It takes as seed a vector of values/times at which to compute the
# the value of the function and a vector with the occurrence times
# of the events.
# Input: eval.times, event.times and values of parameters
# Output: values of intensity function
s<-sort(eval.times)
t<-sort(event.times)
par1<-params[1]
par2<-params[2]
par3<-params[3]
values <- rep(par1,length(s))
for (i in 1:length(values)) {
j<-1
while (t[j] < s[i])
{
values[i] <- values[i] + par2*exp(-par3*(s[i]-t[j]))
j <- j+1
}
}
return(values)
}
然而,當我R中運行它,我得到以下錯誤:Error in while (t[j] < s[i]) { : missing value where TRUE/FALSE needed
。這是什麼意思?上述功能實際上是我試圖提高自己的寫作
Intensity=function(params, eval.times, event.times) {
# This function computes the value of the intensity function.
# It takes as seed a vector of values/times at which to compute the
# the value of the function and a vector with the occurence times
# of the events.
# Input: eval.times, event.times and values of parameters
# Output: values of intensity function
s<-sort(eval.times)
t<-sort(event.times)
par1<-params[1]
par2<-params[2]
par3<-params[3]
values<-foreach(i=seq_along(s), .combine=c) %do% {par1+sum(par2*exp(-par3*(s[i]-t[which(t<s[i])])))}
return(values)
原有功能}
中,我想用一個while
循環來替代sum
和which
因爲我的數組是有序的時間,並能得到相當長。有什麼建議麼?
至於建議,讓我後產生錯誤的數據:如果您檢查T [J]和s的值
event1<-c(3580.794 3583.079 3583.714 3583.998 3584.116 3585.042 3586.264)
seed.times1<-seq(3580, 3590, by=0.001)
hintensity1<-Intensity(c(0.1,5,17), seed.times1, event1)
Error in while (t[j] < s[i]) { : missing value where TRUE/FALSE needed
發佈一些引發錯誤的示例數據。 – 2014-10-03 19:44:46
如果我在相同的數據上使用'which'和'sum'運行函數,我不會收到錯誤... – 2014-10-03 19:50:35