lundi 24 juillet 2017

Writting a function that depends on previous values of itself

I have created the following function

numberstocks <- function (x)
sapply (seq_along(x), function(i) {
    for (i in 1) {
    ifelse (x[i]==0,0,ifelse(x[i]==-1,100,ifelse(x[i]==1,0,0)))
    }
    for (i in 2:2017){
    ifelse (x[i]==0, ifelse(is.numeric(numberstocks(x[i-1]))>-1,numberstocks(x[i-1]),0),ifelse(x[i]==0,0,ifelse(x[i]==-1,100,ifelse(x[i]==1,numberstocks(x[i-1]),0))))
}
})

data5 <- as.data.frame (cbind(data4[1],lapply(data4[,2:2017],numberstocks)))

The function seems to work, however when I run data5 it has been running for about 2 hours now.

Does somebody have a suggestion on how to write the same function in such a way that it doesn't take as long to run?

Thank you in advance

Aucun commentaire:

Enregistrer un commentaire