使用While循环重写用户定义的函数

时间:2014-10-03 19:32:23

标签: r function while-loop

我正在编写以下函数,该函数应该在seed.times中计算强度函数的值。

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)

}

我希望将sumwhich替换为while循环,因为我的数组是有序的,并且可能会很长。有什么建议吗?

根据建议,让我发布产生错误的数据:

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

1 个答案:

答案 0 :(得分:1)

如果你在抛出错误的位置检查t [j]和s [j]的值,我怀疑你会发现两者中的一个是NA。更具体地说,我认为它是[j]。这是因为你允许索引j无限制地增长,所以在某些时候你将超过t向量中的元素数量。尝试在where()控件中包含其他条件。当t的所有元素都是详尽无遗的时候,我不知道你想要发生什么,但这样的事情可能有用:

event1<-c(3580.794, 3583.079, 3583.714, 3583.998, 3584.116, 3585.042, 3586.264) 
seed.times1<-seq(3580, 3590, by=0.001)

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 (!is.na(t[j]) && t[j] < s[i])
     {
         values[i] <- values[i] + par2*exp(-par3*(s[i]-t[j]))
         j <- j+1
      }
    }   

 return(values)
}

hintensity1<-Intensity(c(0.1,5,17), seed.times1, event1)