Conditional Count of changes over time?

conditional-operator, r

Solution

#Some data
dfr <- data.frame(
   binary_variable = runif(100) < .7,
   id = sample(7, 100, replace = TRUE)
)

#Split by id
split_by_id <- with(dfr, split(binary_variable, id))

#Number of changes
sapply(split_by_id, function(x) sum(diff(x) != 0))

Problem

I´d like to count the number of changes of binary factor variable. This variable can change from time to time back and forth multiple times for every user id. Now I´d like to count he number of changes per user id to this variable over a given timespan. The data is sorted by id,year,month,myfactor. I tried this in MySQL but had no success so far. Is there an easy way to do it in R? I though about adding another column to my data.frame and adding up conditions step by step... Maybe some %in% stuff ? Thx in advance for suggestions... Hmm, of course... here´s some example – sorry for not providing it immediately, my head hurts ;): ``` myf Year month userid 1 A 2005 1 260 2 B 2005 2 260 3 B 2005 4 260 4 A 2005 5 260 5 B 2005 6 260 6 B 2005 1 261 ``` if this is my dataset, I want to update the changes column, counting the number of changes of myf per user. Basically id like to end up with: ``` user changes 260 3 260 0 ``` and so forth... HTH

Original source