I have this function in R:
Minimum <- function(data) {
answer <- numeric(length(data))
diference <- c(0, diff(data, lag = 1, differences = 1)) #Padded initially =0
answer[1]=data[1]
for (i in 2:length(diference)) {
if (diference[i]==0) {
answer[i]=answer[i-1]
} else {
answer[i]=data[i]-diference[i]/2
}
}
return(answer)
}
Its purpose is to find the minimum value which "data" could had before it was rounded.
The minimum possible value is the average of the values which "data" had at the last change of value in "data"
This code works, but since for
loops are inefficient in R, it is advised to vectorize the function.
The problem is that the "answer" vector depends on the former values in "answer", so I cannot use a lambda function.
diference[i]==0
will be subject to floating point errors, so not reliable if you are dealing with numeric (non integer) vectors. \$\endgroup\$stopifnot(all(diff(data) >= 0))
. \$\endgroup\$diff(data)
that is not exactly zero and make that your (estimated) rounded precision for all values?Minimum <- function(data) { d <- diff(data); p <- min(d[d > 0]); data - p/2 }
. It's all vectorized, faster, and provides a better (larger) minimum bound on your pre-rounded data. \$\endgroup\$