我想计算序列减少时值之间的差异。有没有计算这个的函数?因为我在网上找不到任何类似的东西。
我的示例:
data.frame(x=c("0","0","2","3","4","1"),diff=c("0","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
我想计算序列减少时值之间的差异。有没有计算这个的函数?因为我在网上找不到任何类似的东西。
我的示例:
data.frame(x=c("0","0","2","3","4","1"),diff=c("0","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
,
使用Collected 2 items
diff
数据
inds <- c(0,diff(df$x))
-inds * (inds < 0)
#[1] 0 0 0 0 0 3 0 4 0