I have data in a long format, similar to the following
id <- c(rep(c(1L,2L,3L),3))
year <- c(rep(c(11,12,13),3))
df <- data.frame(id, year)[-c(8,3),]
df$factor <- factor(c("a", "b", "a", "c", "d","a","d"))
df
I would like to create an indicator variable that takes a value when the factor has changed (e.g. 1 for a change, 0 for no change), on the year the change appears. Is there an efficient way of doing this?
I found this question: Identifying where value changes in R data.frame column which is somewhat related but does not deal with the ids.