R函数,用于从向量中的后续值中减去向量中连续值之间的差值

R函数,用于从向量中的后续值中减去向量中连续值之间的差值,r,function,vector,time-series,R,Function,Vector,Time Series,我有一个数值向量,它包含一个权重数据的时间序列。我需要做的是通过识别连续权重之间不切实际的差异并从序列中的所有后续值中减去该变化来消除权重变化伪影 例如,在系列:c(5,4,6,8,8,9,8,12,10100101101)中,我将第9项和第10项(100-10=90)之间的delta权重识别为伪影,并通过从后续值中减去90来纠正它,得到c(5,4,6,8,8,9,8,12,10,11) 原则上,我的代码类似于: cancel_artifacts <- function(weights,

我有一个数值向量,它包含一个权重数据的时间序列。我需要做的是通过识别连续权重之间不切实际的差异并从序列中的所有后续值中减去该变化来消除权重变化伪影

例如,在系列:c(5,4,6,8,8,9,8,12,10100101101)中,我将第9项和第10项(100-10=90)之间的delta权重识别为伪影,并通过从后续值中减去90来纠正它,得到c(5,4,6,8,8,9,8,12,10,11)

原则上,我的代码类似于:

cancel_artifacts <- function(weights, delta_max) {
    for (i in 0:length(weights)) {
        if (weights[i] - weights[i-1] > abs(delta_max)) {
            weights[i:length(weights)] <- weights[i:length(weights)] - (weights[i] - weights[i-1])
        }
    }
cancel_artifacts abs(delta_max)){

权重[i:length(weights)]您可以通过矢量化的方式执行此操作:

remove_artifacts <- function(weights, delta_max) {
  # calculate deltas, and set first delta to zero
  dw <- c(0, diff(x))
  # create vector of zeros and abs(observations) > delta_max
  # dw * (logical vector) results in either:
  # dw * 0 (if FALSE)
  # dw * 1 (if TRUE)
  dm <- dw * (abs(dw) > delta_max)
  # subtract the cumulative sum of observations > delta_max
  return(weights - cumsum(dm))
}
x <- c(5, 4, 6, 8, 8, 9, 8, 12, 10, 100, 101, 101)
remove_artifacts(x, 50)
# [1]  5  4  6  8  8  9  8 12 10 10 11 11
remove_artifacts delta_max
返回值(权重-总和(dm))
}

对于向量
x,如何调用函数