Zizou
Zizou

Reputation: 503

Calculating differences between next decreasing values

I would like to calculate the difference between the values when the sequences decreases. Is there any function counting this? Because I can't find anything similar on the web.

My example:

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

Upvotes: 1

Views: 88

Answers (2)

Sotos
Sotos

Reputation: 51592

You can simply find the difference, negate it and replace all negative values(showing increase of data) to 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

If you have NAs, then one way to handle them is to make them equal to the previous value, i.e.

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

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 389135

Another way using diff

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

data

df <- type.convert(df)

Upvotes: 2

Related Questions