问题
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, sodate[i-1]
will refer todate[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