[R] stop calculation in a function
Sarah Goslee
sarah.goslee at gmail.com
Thu May 10 14:33:14 CEST 2012
On Thu, May 10, 2012 at 8:02 AM, jeff6868
<geoffrey_klein at etu.u-bourgogne.fr> wrote:
> Thank you for your reply sarah.
> Well actually I don't try to access x[i+1]. The line where you saw it starts
> with #. It was just try I wanted to keep (sorry I should have removed it
> before posting).
Sorry, I should really have more coffee before replying to the list.
Berend makes a good point about st1. You don't provide sample data, so
I can't try it, but here's a modified version of your function that
incorporates his advice plus a calculation of the number of terminal
NA values to skip. I don't know whether x can have internal NA values
as well as terminal, so I wrote a more complex check. If NA values
only appear at the end, you can simply use sum(is.na(x)) instead.
You could also interrupt the loop, but it seems easier to me to
determine the right number of iterations beforehand since you already
have the information needed.
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)
st1 <- numeric(length(x))
endNA <- 0
if(is.na(x[length(x)])) {
endNA <- rle(rev(is.na(x)))$lengths[1]
}
for (i in 2:(length(x)-endNA)){
if((!is.na(x[i]))){
if((tps[i]-tps[ind_temp] < ecart_temps) & (abs(x[i]-temp) > seuil)){
st1[i] <- NA
}
else {
temp <- st1[i] <- x[i]
ind_temp <- i
}
}
}
return(st1)
}
> But I ask him to access to the next value if conditions in the loop are not
> verified (restart the comparison from the next value). It works well as long
> as I have numeric values in my data. But if my data ends with NAs, I have
> this problem.
> That's why I'm trying to ask him to stop the calculation in the loop at the
> last numeric value to avoid this error (don't know if it's the best way to
> solve it, but it's the main idea I think).
> Have you got any other idea about this?
> Thanks a lot!
>
>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list