L55
L55

Reputation: 215

How to determine when a change in value occurs in R

I am following this example from stack overflow: Identifying where value changes in R data.frame column

Theres two columns: ind and value. How do I identify the 'ind' when 'value' increases by 100?

For example,
Value increases by 100 at ind = 4.

df <- data.frame(ind=1:10,
value=as.character(c(100,100,100,200,200,200,300,300,400,400)), stringsAsFactors=F)
df

        ind value
    1    1   100
    2    2   100
    3    3   100
    4    4   200
    5    5   200
    6    6   200
    7    7   300
    8    8   300
    9    9   400
    10  10   400

I tried this but it doesn't work:

 miss <- function(x) ifelse(is.finite(x),x,NA)
 value_xx   =miss(min(df$ind[df$value[1:length(df$value)] >= 100], Inf, na.rm=TRUE))

Upvotes: 0

Views: 1423

Answers (2)

Edo
Edo

Reputation: 7818

Like this:

df$ind[c(FALSE, diff(as.numeric(df$value)) == 100)]

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

You can use diff to get difference between consecutive values and get the index for those where the difference is greater than equal to 100. Added + 1 to the index since diff returns vector which of length 1 shorter than the original one.

df$ind[which(diff(df$value) >= 100) + 1]
#[1] 4 7 9

In dplyr, you can use lag to get previous values :

library(dplyr)
df %>% filter(value - lag(value) >= 100)

#  ind value
#1   4   200
#2   7   300
#3   9   400

Upvotes: 1

Related Questions