# Sample Data
df <- data.frame(scaleDown=c(0,1,0,0,0,0,1,0,0,0,1), scaleUp=c(0,1,0,0,0,0,0,1,0,1,0))
# Function call with mapply
mapply(adjust, df, c(F, T), MoreArgs=list(rate=3, rounding=2))
# scaleDown scaleUp
# [1,] 0.00 0.67
# [2,] 1.00 1.00
# [3,] 0.67 0.00
# [4,] 0.34 0.00
# [5,] 0.00 0.00
# [6,] 0.00 0.34
# [7,] 1.00 0.67
# [8,] 0.67 1.00
# [9,] 0.34 0.50 <{~~
# [10,] 0.00 1.00
# [11,] 1.00 0.00
功能:
adjust <- function(vec, reverse=FALSE, rate=3, rounding=3) {
if (reverse)
vec <- rev(vec)
# add a dummy "1" to end of vec for calculating ends. Will be removed
vec <- c(vec, 1)
len <- length(vec)
indx <- which(vec[-len] != 0)
ends <- c(indx[-1L], (length(vec) + rate))
ranges <- sapply(ends-indx, min, rate)
subtr <- round(vec[indx] / ranges, rounding)
for(i in 1:length(subtr)) {
for (j in (ranges[i]-1):1) {
vec[indx[i] + ranges[i]-j] <- vec[indx[i] + ranges[i]-j-1] - subtr[i]
}
}
# remove dummy element
vec <- vec[seq(len-1)]
if (reverse)
return(rev(vec))
return(vec)
}