R函数从向量的后续值中减去向量的连续值之间的差 [英] R function to subtract the difference between consecutive values in vector from subsequent values in vector

查看:49
本文介绍了R函数从向量的后续值中减去向量的连续值之间的差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a numerical vector that contains a time series of weight data. What I need to do is remove weight change artifacts by identifying unrealistic differences between consecutive weights and subtracting that change from all subsequent values in the series.

例如,在系列:c(5,4,6,8,8,9,8,12,10,100,101,101)中,我将第9项和第10项(100-10 = 90)之间的增量权重标识为一个伪像,我会通过从后续值中减去90来更正它,得出c(5,4,6,8,8,9,8,12,10,10,11,11).

For example, in the series: c(5,4,6,8,8,9,8,12,10,100,101,101), I would identify the delta weight between items 9 and 10 (100 - 10 = 90) as an artifact, and I would correct it by subtracting 90 from the subsequent values, yielding c(5,4,6,8,8,9,8,12,10,10,11,11).

原则上,我的代码如下所示:

In principal, my code would look something like:

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])
        }
    }

很明显,我的语法简直是一场灾难.有人可以帮我设置吗?

Obviously my syntax is a disaster. Can anyone help me set this up?

推荐答案

您可以采用矢量化方式进行操作:

You can do this in a vectorized manner:

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

这篇关于R函数从向量的后续值中减去向量的连续值之间的差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆