[R] stop calculation in a function

jeff6868 geoffrey_klein at etu.u-bourgogne.fr
Thu May 10 11:14:26 CEST 2012


Hi dear R-users,

I have a question about a function I'm trying to improve.
How can I stop the function calculation at the last numeric value of my
data?
The problem is that the end of my data contains missing values (NAs). And
the aim of my function is to compare the first numeric value with the next
one (till the end). For the moment, It works well when my data doesn't
contains any NAs at the end of my file. I think that the problem is, as I
have NAs at the end of my data, R tries to compare my last numeric value
with the next numeric value wich doesn't exists, and so tries to modify the
length of my data (the error message is that the output has not the same
length as the input).
Could somebody tell me what I should modify or add in my function in order
to fix this problem?
Here's the function. Thanks for your advises! 

out2NA <- function(x,seuil){
    st1 = NULL
    # Temporal variable memorysing the last "correct" numeric value#
    temp <- st1[1] <- x[1]
    ind_temp <- 1
    # Max time gap between two comparisons #
    ecart_temps <- 10
    tps <- time(x)

    for (i in 2:length(x)){
    if((!is.na(x[i]))){
    if((tps[i]-tps[ind_temp] < ecart_temps) & (abs(x[i]-temp) > seuil)){
    #&(abs(x[i+1]-x[i])<1)){
    st1[i] <- NA
    }
    else {
    temp <- st1[i] <- x[i]
    ind_temp <- i
    }
    }
    }
    return(st1)
    }

    dat1 <- myts[,2]
    myts[,2] <- apply(dat1,2,function(x) out2NA(x,2))

--
View this message in context: http://r.789695.n4.nabble.com/stop-calculation-in-a-function-tp4622964.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list