Chris
Chris

Reputation: 55

r count successive instances of variable combinations

I need to enumerate successive instances of variable combinations, within a combination of 2 variables. Within the subset of one variable (Id) a counting variable should enumerate similar niveaus of another variable (price) and advance every time there is a niveau change.

I tried the ave() function for this, but can't find the proper aggreagation function to get it to work as I want.

# Id is a factor
df <- data.frame(Id = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2), price = c(10, 20, 20, 20, 10, 10, 10, 10, 20, 10, 10))

   Id price
1   1    10
2   1    20
3   1    20
4   1    20
5   1    10
6   1    10
7   1    10
8   2    10
9   2    20
10  2    10
11  2    10

my ecpected output is

   Id price expected_output
1   1    10               1
2   1    20               2
3   1    20               2
4   1    20               2
5   1    10               3
6   1    10               3
7   1    10               3
8   2    10               1
9   2    20               2
10  2    10               3
11  2    10               3

Upvotes: 2

Views: 241

Answers (1)

akrun
akrun

Reputation: 887531

 df$expected_output <- with(df,ave(price,Id,FUN=function(x) 
         cumsum(c(T,x[-1]!=x[-length(x)])) )) 

 df$expected_output 
     #[1] 1 2 2 2 3 3 3 1 2 3 3

Or

library(dplyr)
df%>%
group_by(Id) %>% 
mutate(expected_output= cumsum(c(T,diff(price)!=0)))

Upvotes: 1

Related Questions