Well, if i goes from 2 to length(x) and you try to access x[i+1], of course odd things will happen. Why not construct the loop to (length(x)-1) instead, so that x[i+1] is defined.
Sarah On Thu, May 10, 2012 at 5:14 AM, jeff6868 <[email protected]> wrote: > 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)) > > -- -- Sarah Goslee http://www.functionaldiversity.org ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.

