计算下一个递减值之间的差异

Calculating differences between next decreasing values

我想计算序列减少时值之间的差异。有没有计算这个的功能?因为我在网上找不到类似的东西。

我的例子:

data.frame(x=c("0", "0", "2", "2","3", "0", "4", "0", "1"), 
           diff=c("0","0", "0", "0", "0","3", "0", "4", "0"))

  x diff
1 0    0
2 0    0
3 2    0
4 2    0
5 3    0
6 0    3
7 4    0
8 0    4
9 1    0

您可以简单地找到差异,取反并将所有负值(显示数据增加)替换为 0

#convert to numeric first
dd[] <-lapply(dd, function(i)as.numeric(as.character(i)))

replace(-diff(dd$x), -diff(dd$x) < 0 ,  0)
#[1] 0 0 0 0 3 0 4 0

如果你有 NA,那么处理它们的一种方法是使它们等于以前的值,即

x <- c(5, NA, 2) #Notice how I DON'T put them in quotes so it's numeric
x1 <- replace(x, is.na(x), x[which(is.na(x)) - 1])

#Using the same method as above on the new x1,
c(0, replace(-diff(x1), - diff(x1) < 0, 0))
#[1] 0 0 3

另一种使用方式 diff

inds <- c(0, diff(df$x))
-inds * (inds < 0)
#[1] 0 0 0 0 0 3 0 4 0

数据

df <- type.convert(df)