简体   繁体   中英

function with vector R - argument is of length zero

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)

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM