Reputation: 315
I am trying to recoding a existing data with a overtime structure. My dataset looks like this:
dput(z)
structure(list(democracy = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), year.x = 1967:2008, time = c(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42)), .Names = c("democracy", "year.x", "time"), row.names = 176:217, class = "data.frame")
So that I want to create a new variable, say, time.democ, which takes the value of zero if democracy==0
but start counting the time period again, starting from 1, if democracy ==1
, until democracy==0
again. I'm going to do it for a series of countries but I am assuming thr generalization is easy enough using ddply if once I get this function right. Any suggestions?
I would like to get this:
dput(z)
structure(list(democracy = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), year.x = 1967:2008, time = c(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42), new.time = c(0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0,
0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25)), .Names = c("democracy",
"year.x", "time", "new.time"), row.names = 176:217, class = "data.frame")
Thanks!
Upvotes: 0
Views: 299
Reputation: 315
Thanks for your replies. I followed your suggestions and I end up writing a function so that I can apply this to all units in my (longitudinal) data set via ddply. I am posting it as it might help some else, though I am sure there are more elegant solutions:
# is a long format data frame
new.time <- function(a){
a <- a[order(a$year.x),]
a$new.time <- sequence(rle(a$democracy)$lengths)-1
a$new.time[a$democracy==0] <- 0
return(a)
}
merged1 <- ddply(merged, .(country.x), new.time)
Upvotes: 0
Reputation: 179428
You can use rle
combined with sequence
to do this. rle
performs run length encoding, while sequence
generates sequences.
z$new.time <- sequence(rle(z$democracy)$lengths)
z$new.time[z$democracy==0] <- 0
head(z, 20)
democracy year.x time new.time
176 0 1967 1 0
177 0 1968 2 0
178 0 1969 3 0
179 0 1970 4 0
180 0 1971 5 0
181 0 1972 6 0
182 1 1973 7 1
183 1 1974 8 2
184 1 1975 9 3
185 0 1976 10 0
186 0 1977 11 0
187 0 1978 12 0
188 0 1979 13 0
189 0 1980 14 0
190 0 1981 15 0
191 0 1982 16 0
192 1 1983 17 1
193 1 1984 18 2
194 1 1985 19 3
195 1 1986 20 4
Upvotes: 1