I want to create time duration variable in r but I haven't figure it out. My data looks like this:
company <- rep(c("A", "B"), each=8)
year <- rep(1980:1987, 2)
value <- c(NA,0,0,0,1,0,-1,1,NA,-3,NA,0,0,1,0,0)
data <- data.frame(company, year, value)
I want it like this
company <- rep(c("A", "B"), each=8)
year <- rep(1980:1987, 2)
value <- c(NA,0,0,0,1,0,-1,1,NA,-3,NA,0,0,1,0,0)
timeduration <- c(NA,1,2,3,1,2,1,1,NA,1,NA,1,2,1,2,3)
data1 <- data.frame(company, year, value, timeduration)
Zero(s) has two meanings in the value variable. If I use it after NA, I have to start counting from 1, but if 0 comes from after any value, it means that change in the value is constant. Therefore, I have to continue to count even if the value is changed to 0. I show this situation in the second data (data1). (Also, data should be grouped by considering companies). Thank you for your efforts!