function with vector R - argument is of length zero

此生再无相见时 提交于 2020-12-15 05:32:43

问题


Wrote this function lockdown_func(beta.hat_func).

First thing is: I get an error "argument is of length zero". Second thing is: when I compute it without the date indices, it doesn't change the value as it should, output vector contains same value for every indices.

date= c(seq(from=30, to=165))
beta.hat_func <- c(rep(x = beta.hat, times = 135))
beta.hat <- beta0[which.min(SSE)]


#implement function for modeling
lockdown_func <- function(beta.hat_func,l){
  h=beta.hat_func
  {
    for(i in 1:length(h))
      if(date[i]>60 | date[i]<110){
        beta.hat_func[i]=beta.hat_func[i]*exp(-l*(date[i]-date[i-1]))
    }else{
    beta.hat_func[i]=beta.hat_func[i]
    }
  return(h)  
  }
}

lockdown_func(beta.hat_func,0.03)

回答1:


A few comments:

  • did you mean to apply an AND rather than an OR to get date range between 60 and 110? This would be date[i]>60 && date[i]<110 (it's better to use the double-&& if you are computing a length-1 logical value)
  • because you didn't, i=1 satisfies the criterion, so date[i-1] will refer to date[0], which is a length-0 vector.

You might want something like:

l_dates <- date>60 & date<110  ## single-& here for vectorized operation
beta.hat_func[l_dates] <- beta.hat_func[l_dates]*exp(-l*diff(date)[l_dates])


来源:https://stackoverflow.com/questions/65180258/function-with-vector-r-argument-is-of-length-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!